3

我正在努力理解以下代码的行为:

let a: Any? = nil
let b: AnyObject? = a as AnyObject

if let c: AnyObject = b {
    print(c)
    print("That's not right, is it?")
} else {
    print("I'd expect this to be printed")
}

在 Playground 中运行时,虽然 a 为 nil,但执行第一个闭包并打印以下内容:

<null>
不对,是吗?

问:这怎么可能?这是预期的行为吗?

4

2 回答 2

6

a as AnyObjecta转换为NSNullb为零

你可以检查它type(of:)

let a: Any? = nil
let b: AnyObject? = a as AnyObject

if let c: AnyObject = b {
    print(c)
    print(type(of: c)) // will print "NSNull"
    print("That's not right, is it?")
} else {
    print("I'd expect this to be printed")
}
于 2018-05-29T08:46:53.960 回答
2

因为<null>不是nilAnyObject是一种连接到 Objective-C 空间的类型。

于 2018-05-29T08:48:44.683 回答