我正在尝试使用快速反射来检查对象中的更改,以便我只能将更改的属性发送到服务器.我的一些属性是可选的.为了比较这些值,我需要打开它们,但是,当然,你只能打开实际值,而不是nil值
在我的操场上,我尝试了以下方法:
import UIKit class myClass { var fieldOne:String? var fieldTwo:Int? var fieldThree:Float? } var oneMyClass = myClass() oneMyClass.fieldOne = "blah" oneMyClass.fieldThree = 3.5 var oneOtherClass = myClass() oneOtherClass.fieldOne = "stuff" oneOtherClass.fieldTwo = 3 let aMirror = Mirror(reflecting: oneMyClass) let bMirror = Mirror(reflecting: oneOtherClass) for thing in aMirror.children { for thing2 in bMirror.children { if thing.label! == thing2.label! { print("property: \(thing.label!)") print("before: \(thing.value)") print("after: \(thing2.value)") print("") //let myTest = thing.value == nil ? "nil" : "not nil" } } }
它会生成以下输出:
property: fieldOne before: Optional("blah") after: Optional("stuff") property: fieldTwo before: nil after: Optional(3) property: fieldThree before: Optional(3.5) after: nil
如您所见,预期属性显示为“nil”.但是,如果取消注释let语句,则会收到错误消息:
playground52.swift:37:38: error: value of type 'Any' (aka 'protocol<>') can never be nil, comparison isn't allowed
然而,我们从输出中知道它是零.这怎么可能,我该怎么办呢?
那看起来像某种bug.看那个let x = childMirror.value == nil ? "Nil" : "Not Nil" //dont compile. let y = { (value:Any?) in return value == nil ? "Nil" : "Not Nil" } let z = y(childMirror.value) //compile, but doesn't evaluate.
我猜问题是因为Any可以存储一个Optional,但不能包含一个.试试这个:
func getValue(unknownValue:Any) -> Any { let value = Mirror(reflecting: unknownValue) if value.displayStyle != .Optional || value.children.count != 0 { return "Not Nil" } else { return "Nil" } }