如何检查字典中是否存在密钥?我的字典是类型的[Type:Type?].
我不能简单地检查dictionary[key] == nil,因为这可能是由于价值所致nil.
有任何想法吗?
Mar*_*n R 66
实际上,您的测试dictionary[key] == nil 可用于检查字典中是否存在密钥.true如果值设置为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
Run Code Online (Sandbox Code Playgroud)
要区分"密钥在dict中不存在"和"密钥值为零",您可以执行嵌套的可选赋值:
if let val = dict["key"] {
if let x = val {
println(x)
} else {
println("value is nil")
}
} else {
println("key is not present in dict")
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*lum 41
我相信字典类型indexForKey(key: Key)是你正在寻找的.它返回给定键的索引,但更重要的是对于您的建议,如果它无法在字典中找到指定的键,则返回nil.
if dictionary.indexForKey("someKey") != nil {
// the key exists in the dictionary
}
Run Code Online (Sandbox Code Playgroud)
Swift 3语法....
if dictionary.index(forKey: "someKey") == nil {
print("the key 'someKey' is NOT in the dictionary")
}
Run Code Online (Sandbox Code Playgroud)
您可以随时这样做:
let arrayOfKeys = dictionary.allKeys
if arrayOfKeys.containsObject(yourKey) {
}
else {
}
Run Code Online (Sandbox Code Playgroud)
但是,我真的不喜欢创建可以包含可选内容的NSDictionary的想法。
| 归档时间: |
|
| 查看次数: |
58681 次 |
| 最近记录: |