我正在尝试使用快速反射来检查对象中的更改,这样我就只能将更改后的属性发送到服务器。我的一些属性是可选的。要比较这些值,我需要打开它们,但当然,您只能打开实际值,而不能打开零值。所以,在比较它们之前,我需要检查其中一个值是否为零。
在我的操场上,我尝试了以下方法:
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
然而,我们从产出中知道,它是零。这怎么可能?我该怎么办?
基于这个答案,我建议使用if case Optional<Any>.some(_)
。
例如:
aMirror.children.forEach {
guard let propertyName = $0.label else { return }
if case Optional<Any>.some(_) = $0.value {
print("property: (propertyName) is not nil")
} else {
print("property: (propertyName) is nil")
}
}
这看起来像是某种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"
}
}