本文介绍了为什么我仍然需要解开 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]!
    }
}

我收到错误:可选类型字符串?"的值未解包.

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

Why do I need to use ! after X.global[type]? I'm not using any optional in my dictionary?

已编辑:

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

Even if X.global[type] may not exist for the type, force unwrapping will still crash on runtime. A better approach may be:

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

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

but Xcode is giving me the wrong idea by hinting about optional type.

推荐答案

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

Dictionary accessor returns optional of its value type because it does not "know" run-time whether certain key is there in the dictionary or not. If it's present, then the associated value is returned, but if it's not then you get nil.

来自 文档:

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

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

In order to handle the situation properly you need to unwrap the returned 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 字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:26
查看更多