我有以下代码,它说明了一个我还没有想好如何干净利落地解决的问题,即:
如何使函数(IsNil)既对nil返回True,又对可选函数(Nil)返回True,而对其他任何内容返回False?
class Foo {
var baz : Date? = nil
subscript(key: String) -> Any? {
get {
let m = Mirror(reflecting: self)
for child in m.children {
if (child.label == key) { return child.value }
}
return nil
}
}
}
// this works unless the field is an Optional(nil)
func isNil(_ field: Any?) -> Bool {
if field == nil { return true }
return false
}
// this sort of works in a really terrible hacked way
func isNilViaString(_ field: Any?) -> Bool {
if field == nil { return true }
return "\(field.debugDescription)" == "Optional(nil)"
}
// this returns true as expected
print("isNil(nil) = \(isNil(nil))")
var optionalNil = Foo()["baz"]
// I'd like this to return true as well
print("isNil(optionalNil) = \(isNil(optionalNil))")
// this returns true, but is super hacky
print("isNilViaString(optionalNil) = \(isNilViaString(optionalNil))")
// this is an example of a problem with the isNilViaString method
print("isNilViaString(optionalNil) = \(isNilViaString("Optional(nil)"))")