swift - 如何快速检查 `Any(not Any?)` 是否为零

标签 swift

我在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测试是否 anil :

var b: Bool?
var a = b as Any
if case Optional<Any>.none = a {
    print("nil")
} else {
    print("not nil")
}
nil
b = true
a = b as Any
if case Optional<Any>.none = a {
    print("nil")
} else {
    print("not nil")
}
not nil
<小时/>

使用 switch :

您可以使用 switch 进行模式测试还有:

var b: Bool?
var a = b as Any

switch a {
case Optional<Any>.none:
    print("nil")
default:
    print("not nil")
}
nil

关于swift - 如何快速检查 `Any(not Any?)` 是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010893/

相关文章:

ios - 如何 NotificationCenter#addObserver(forName :object:queue:using:) works?

ios - 如何检测 30 秒持续时间

ios - 如何在 draw(_ rect : CGRect) in Swift 中使用不同的混合模式绘制 UILabel

ios - 允许 UIAnimations 中的 UITapGestureRecognizer

ios - 如何使用 afnetworking 2.0 的可达性在互联网消失后立即向用户显示消息

json - 如何过滤 JSON 数据解析器

arrays - 如何获取数组/字典的切片并追加

Swift 在 for 循环中混淆 "unresolved identifier"

ios - RxSwift 过滤器变量数组

ios - 如何将代码添加到我的 viewcontroller.swift 以通过导航 Controller 连接的 View ?