[英]Check if key exists in dictionary of type [Type:Type?]
如何检查字典中是否存在键? 我的字典是[Type:Type?]
。
我不能简单地检查dictionary[key] == nil
,因为这可能是由于值为nil
。
有任何想法吗?
实际上,您的 test dictionary[key] == nil
可用于检查字典中是否存在键。 如果该值设置为nil
,则不会产生true
:
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
要区分“字典中不存在键”和“键的值为 nil”,您可以进行嵌套的可选赋值:
if let val = dict["key"] {
if let x = val {
println(x)
} else {
println("value is nil")
}
} else {
println("key is not present in dict")
}
我相信 Dictionary 类型的indexForKey(key: Key)
就是你要找的。 它返回给定键的索引,但对于您的提议更重要的是,如果在字典中找不到指定的键,它将返回 nil。
if dictionary.indexForKey("someKey") != nil {
// the key exists in the dictionary
}
Swift 3 语法....
if dictionary.index(forKey: "someKey") == nil {
print("the key 'someKey' is NOT in the dictionary")
}
你总是可以这样做:
let arrayOfKeys = dictionary.allKeys
if arrayOfKeys.containsObject(yourKey) {
}
else {
}
然而,我真的不喜欢创建一个可以包含可选项的 NSDictionary 的想法。
尝试这个:
let value = dict[key] != nil
希望它对你有用。 谢谢
正如这里和上面所建议的,最好的解决方案是使用Dictionary.index(forKey:)
返回Dictionary<Key, Value>.Index?
. 无论您的值是否是可选类型,这都会返回一个可选索引,如果为nil
,则明确地告诉您该键是否存在于字典中。 这比使用Dictionary.contains(where:)
更有效Dictionary.contains(where:)
它被记录为具有“复杂度 O( n ),其中n是序列的长度”。
因此,编写.containsKey()
更好方法是:
extension Dictionary {
func contains(key: Key) -> Bool {
self.index(forKey: key) != nil
}
}
我被告知dict.keys.contains() 实际上是 O(1) ,所以如果你愿意,可以随意使用它。
我在 Swift 4 中是这样处理的:
extension Dictionary {
func contains(key: Key) -> Bool {
let value = self.contains { (k,_) -> Bool in key == k }
return value
}
}
这使用Dictionary.contains(where: (key: Hashable, value: Value) throws -> Bool)
。 通过将它封装为扩展,我可以在不修改代码的情况下将实现更新为更好的东西。 我避免创建数据,而index(forKey:Key)
。 我希望它比访问keys
更有效,因为它必须在搜索之前创建整个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.