为什么我还需要打开Swift字典值呢?

son*_*nce 8 optional swift

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]!
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到了错误:Value of optional type 'String?' not unwrapped.

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

编辑:

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

if let valExist = X.global[type] {
}
Run Code Online (Sandbox Code Playgroud)

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

cou*_*elk 9

字典访问器返回其值类型的可选项,因为它不"知道"运行时字典中是否存在某些键.如果它存在,则返回相关的值,但如果不存在则返回nil.

文档:

您还可以使用下标语法从字典中检索特定键的值.因为可以请求不存在值的键,所以字典的下标返回字典值类型的可选值.如果字典包含所请求键的值,则下标返回包含该键的现有值的可选值.否则,下标返回nil ...

为了正确处理这种情况,你需要打开返回的可选项.

有几种方法:

选项1:

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

选项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
}
Run Code Online (Sandbox Code Playgroud)

选项3:

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