I've got the following code, which illustrates a problem I haven't figured out how to solve cleanly, that is:
How can I make a function (isNil) that will return true for both nil, and Optional(nil), but false for anything else?
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)"))")