我很难理解以下代码的行为:
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")
}
在游乐场中运行时,虽然a为nil,但执行第一个闭包并打印以下内容:
<空>
这不对,是吗?
问:这怎么可能,是预期的行为?
答案 0 :(得分:6)
a as AnyObject
会将a
投放到NSNull
,以便b
不是
您可以使用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")
}
答案 1 :(得分:2)
因为<null>
不是nil
。 AnyObject
是一种桥接到Objective-C空间的类型。