检查键中是否存在键[类型:类型?]

vrw*_*wim 34 swift

如何检查字典中是否存在密钥?我的字典是类型的[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)

  • @vrwim:`dict ["b"]`是一个"嵌套的可选",它的类型是`Int ??`,真正的值是`.Some(.None <Int>)`:)你可以阅读更多关于它的内容在Swift博客中https://developer.apple.com/swift/blog/?id=12.另请参阅此答案http://stackoverflow.com/a/27226589/1187415以获取相关问题. (8认同)
  • @JoeBlow:`dict.keys.contains(key)`将是另一个选项(Swift 2 + 3). (5认同)

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)


Lor*_*olt 5

您可以随时这样做:

let arrayOfKeys = dictionary.allKeys
if arrayOfKeys.containsObject(yourKey) {

}
else {
}
Run Code Online (Sandbox Code Playgroud)

但是,我真的不喜欢创建可以包含可选内容的NSDictionary的想法。

  • 我想使用Swift类型,而不是NSArray (2认同)