小编flo*_*ger的帖子

Nil检查并不总是在Swift中为Any工作

当我使用Any类型时,我对Swift如何检查nil感到困惑.
这是一个例子:

let testA: Any? = nil
let testB: Any = testA as Any
let testC: Any? = testB

if testA != nil {
    print(testA) // is not called as expected
}
if testB != nil {
    print(testB) // prints "nil"
}
if testC != nil {
    print(testC) // prints "Optional(nil)"
}
Run Code Online (Sandbox Code Playgroud)

testA按预期工作.变量为nil,因此条件为false.

testB的工作并不像预期的那样.变量为nil,如打印调用所示.但条件testB != nil评估为真.为什么会这样?

testC也困惑我,因为它是testC = testB = testA.那么为什么它的行为与testA不同呢?

我怎么需要写if条件if testB ...if testC ...不是真的.
我正在寻找一种不需要我知道类型的解决方案,比如......

if let …
Run Code Online (Sandbox Code Playgroud)

swift

9
推荐指数
1
解决办法
296
查看次数

标签 统计

swift ×1