检查 [Type:Type?] 类型的字典中是否存在键

编程入门 行业动态 更新时间:2024-10-27 04:31:53
本文介绍了检查 [Type:Type?] 类型的字典中是否存在键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何检查字典中是否存在键?我的字典属于 [Type:Type?] 类型.

How can I check if a key exists in a dictionary? My dictionary is of type [Type:Type?].

我不能简单地检查 dictionary[key] == nil,因为这可能是由 nil 的值造成的.

I can't simply check dictionary[key] == nil, as that could result from the value being nil.

有什么想法吗?

推荐答案

其实你的测试dictionary[key] == nil 可以用来检查如果字典中存在键.它不会产生 true 如果值设置为 nil:

Actually your test dictionary[key] == nil can be used to check if a key exists in a dictionary. It will not yield true if the value is set to nil:

let dict : [String : Int?] = ["a" : 1, "b" : nil] dict["a"] == nil // false, dict["a"] is .Some(.Some(1)) dict["b"] == nil // false !!, dict["b"] is .Some(.None) dict["c"] == nil // true, dict["c"] is .None

要区分字典中不存在键"和键的值为零",您可以做一个嵌套的可选赋值:

To distinguish between "key is not present in dict" and "value for key is nil" you can do a nested optional assignment:

if let val = dict["key"] { if let x = val { println(x) } else { println("value is nil") } } else { println("key is not present in dict") }

更多推荐

检查 [Type:Type?] 类型的字典中是否存在键

本文发布于:2023-11-05 15:58:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否存在   字典   类型   Type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!