我在swift中使用Mirror
,我发现Mirror.Child
很奇怪,标签可以为空,但值似乎不能为空。
public typealias Child = (label: String?, value: Any)
我不知道如何检查该值是否为零。
let b: Bool? = true
let a: Any = b
print(a == nil) // false
我有一个解决方案:
print(String(describing: a) == "nil") // true
但这显然不是一个好的解决方案。
检查 a
是否为零的最佳方法是什么?
让我提供更多细节,
let mirror = Mirror(reflecting: object) // object can be any object.
for child in mirror.children {
guard let label = child.label else {
continue
}
// how to check if the value is nil or not here ?
setValue(child.value, forKey: label)
}
最佳答案
使用 if case
:
您可以使用if case Optional<Any>.none = a
测试是否 a
是 nil
:
var b: Bool?
var a = b as Any
if case Optional<Any>.none = a {
print("nil")
} else {
print("not nil")
}
block 引用>nil
b = true a = b as Any if case Optional<Any>.none = a { print("nil") } else { print("not nil") }
block 引用> <小时/>not nil
使用
switch
:您可以使用
switch
进行模式测试还有:var b: Bool? var a = b as Any switch a { case Optional<Any>.none: print("nil") default: print("not nil") }
block 引用>nil
关于swift - 如何快速检查 `Any(not Any?)` 是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010893/