快速反射会导致任何值都不可能产生零值

asp*_*pro 5 reflection swift

我正在尝试使用快速反射来检查对象中的更改,以便仅将更改后的属性发送到服务器。我的一些属性是可选的。要比较这些值,我需要解开它们,但是,当然,您只能解开实际值,而不是nil值。因此,我需要在比较它们之前检查其中一个值是否为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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并生成以下输出:

property: fieldOne
before: Optional("blah")
after: Optional("stuff")

property: fieldTwo
before: nil
after: Optional(3)

property: fieldThree
before: Optional(3.5)
after: nil
Run Code Online (Sandbox Code Playgroud)

如您所见,期望的属性显示为“ nil”。但是,如果取消注释let语句,则会出现错误,指出:

playground52.swift:37:38: error: value of type 'Any' (aka 'protocol<>') can never be nil, comparison isn't allowed
Run Code Online (Sandbox Code Playgroud)

但是,从输出中我们知道它为零。怎么会这样,我该怎么办?

n8t*_*8tr 8

基于此答案,我建议使用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")
    }
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*ück 3

那看起来像是某种错误。看那个

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.
Run Code Online (Sandbox Code Playgroud)

我想问题是因为 Any 可以存储可选,但不能包裹可选。尝试这个:

func getValue(unknownValue:Any) -> Any {

    let value = Mirror(reflecting: unknownValue)
    if value.displayStyle != .Optional || value.children.count != 0 {
        return "Not Nil"
    } else {
        return "Nil"
    }
}
Run Code Online (Sandbox Code Playgroud)