加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:44:06 所属栏目:百科 来源:网络整理
导读: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]! }} 我收到错误:可选类型’String?’的值没有打开. 我为什么需要使用!在X.global [type]之
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]!
    }
}

我收到错误:可选类型’String?’的值没有打开.

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

编辑:

即使该类型可能不存在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…

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

有几种方法:

选项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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读