奇怪的是什么?作为AnyObject行为

时间:2018-05-29 08:23:39

标签: swift casting optional anyobject

我很难理解以下代码的行为:

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,但执行第一个闭包并打印以下内容:

  

<空>
  这不对,是吗?

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

2 个答案:

答案 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>不是nilAnyObject是一种桥接到Objective-C空间的类型。