如何在swift中检查`Any(not Any?)`是否为nil

JIE*_*ANG 8 swift

我正在使用Mirrorswift,我发现Mirror.Child很奇怪,标签是可以为空的,但是值似乎不可为空.

public typealias Child = (label: String?, value: Any)
Run Code Online (Sandbox Code Playgroud)

我不知道如何检查值是否为零.

let b: Bool? = true
let a: Any = b
print(a == nil) // false
Run Code Online (Sandbox Code Playgroud)

我有一个解决方案:

print(String(describing: a) == "nil") // true
Run Code Online (Sandbox Code Playgroud)

但这显然不是一个好的解决方案.

检查是否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)
}
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 16

使用if case:

您可以使用if case Optional<Any>.none = a,以测试是否anil:

var b: Bool?
var a = b as Any
if case Optional<Any>.none = a {
    print("nil")
} else {
    print("not nil")
}
Run Code Online (Sandbox Code Playgroud)
nil
Run Code Online (Sandbox Code Playgroud)
b = true
a = b as Any
if case Optional<Any>.none = a {
    print("nil")
} else {
    print("not nil")
}
Run Code Online (Sandbox Code Playgroud)
not nil
Run Code Online (Sandbox Code Playgroud)

使用switch:

您也可以使用模式测试switch:

var b: Bool?
var a = b as Any

switch a {
case Optional<Any>.none:
    print("nil")
default:
    print("not nil")
}
Run Code Online (Sandbox Code Playgroud)
nil
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@AshleyMills。我在答案中添加了“switch”。 (3认同)
  • 不错的答案,但使用 `switch` 而不是 `if case` 可能更清楚 (2认同)