gpt4 book ai didi

swift - 为什么我仍然需要解开 Swift 字典值?

转载 作者:行者123 更新时间:2023-11-30 12:50:17 27 4
gpt4 key购买 nike

class X {
static let global: [String:String] = [
"x":"x data",
"y":"y data",
"z":"z data"
]

func test(){
let type = "x"
var data:String = X.global[type]!
}
}

我收到错误:可选类型“字符串”的值?未打开

为什么我需要在 X.global[type] 之后使用 !?我的字典中没有使用任何 optional ?

已编辑:

即使该类型可能不存在X.global[type],强制展开仍然会在运行时崩溃。更好的方法可能是:

if let valExist = X.global[type] {
}

但是 Xcode 通过暗示可选类型给了我错误的想法。

最佳答案

字典访问器返回其值类型的可选值,因为它不“知道”运行时字典中是否存在某个键。如果存在,则返回关联的值,但如果不存在,则返回 nil

来自documentation :

You can also use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil...

为了正确处理这种情况,您需要解开返回的 optional 。

有几种方法:

选项 1:

func test(){
let type = "x"
if var data = X.global[type] {
// Do something with data
}
}

选项 2:

func test(){
let type = "x"
guard var data = X.global[type] else {
// Handle missing value for "type", then either "return" or "break"
}

// Do something with data
}

选项 3:

func test(){
let type = "x"
var data = X.global[type] ?? "Default value for missing keys"
}

关于swift - 为什么我仍然需要解开 Swift 字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41099714/

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