gpt4 book ai didi

swift - 奇怪吗?作为 AnyObject 行为

转载 作者:搜寻专家 更新时间:2023-10-31 21:58:50 26 4
gpt4 key购买 nike

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

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>
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")
}

关于swift - 奇怪吗?作为 AnyObject 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50579601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com