奇怪吗?作为 AnyObject 行为
Strange Any? as AnyObject behaviour
我很难理解以下代码的行为:
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,但执行第一个闭包并打印以下内容:
<null>
That's not right, is it?
问:这怎么可能,这是预期的行为吗?
a as AnyObject
会将 a
转换为 NSNull
这样 b
就不是 nil
你可以用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")
}
因为 <null>
不是 nil
。 AnyObject
是桥接到 Objective-C space.
的类型
我很难理解以下代码的行为:
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,但执行第一个闭包并打印以下内容:
<null>
That's not right, is it?
问:这怎么可能,这是预期的行为吗?
a as AnyObject
会将 a
转换为 NSNull
这样 b
就不是 nil
你可以用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")
}
因为 <null>
不是 nil
。 AnyObject
是桥接到 Objective-C space.