gpt4 book ai didi

swift - 不可预测的 nil 检查结果

转载 作者:搜寻专家 更新时间:2023-10-31 22:43:41 25 4
gpt4 key购买 nike

不可预测(不明显)nil检查:

这个函数:

fileprivate func isPurchased(_ name: String) -> Bool {
if let _ = dictionary[name] {
return true
} else {
return false
}
}

返回 true对于:

fileprivate var dictionary = [String: Double?]()

false对于 [String: Double] (这很正常)。为什么?

我初始化 dictionary像这样:

dictionary["test"] = nil

我的意思是:

isPurchased("test")返回 true对于 [String: Double?]

isPurchased("test")返回 false对于 [String: Double]

更新

 var dictionary = [String: Double?]()
dictionary["test"] = nil
print("\(isPurchased("test"))")

打印 true

 var dictionary = [String: Double]()
dictionary["test"] = nil
print("\(isPurchased("test"))")

打印 false

为什么?

最佳答案

首先,不要使用 if let 来检查是否为 nil。只需使用 value == nil

正如评论中所讨论的那样,从类型为 [String: Double?] 的字典中获取带有下标的值会导致 double-optional (Double?? ).

这意味着 dictionary[name] 的值为 Optional.some(Optional.none)

要解决这个问题,您可以执行以下操作:

if let value = dictionary["test"], value != nil 

关于swift - 不可预测的 nil 检查结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938321/

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