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

时间:2023-01-12 17:01:15

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

如何检查字典中是否存在键?我的字典是打字的。

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

我不能简单地检查字典[key] == nil,因为这可能会导致值为nil。

Any ideas?

什么好主意吗?

6 个解决方案

#1


59  

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:

实际上,您的测试字典[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

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

要区分“关键不在词典中”和“关键的值是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")
}

#2


29  

I believe the Dictionary type's indexForKey(key: Key) is what you're looking for. It returns the index for a given key, but more importantly for your proposes, it returns nil if it can't find the specified key in the dictionary.

我相信字典类型的indexForKey(key: key)就是你要找的。它返回给定键的索引,但更重要的是对于您的提议,如果在字典中找不到指定键,它将返回nil。

if dictionary.indexForKey("someKey") != nil {
    // the key exists in the dictionary
}

Swift 3 syntax....

斯威夫特3语法....

if dictionary.index(forKey: "someKey") == nil {
    print("the key 'someKey' is NOT in the dictionary")
}

#3


2  

You can always do:

你可以做的:

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

}
else {
}

However I really dislike the idea of creating an NSDictionary which can contain optionals.

然而,我真的不喜欢创建一个包含optionals的NSDictionary。

#4


1  

Try this:

试试这个:

let value = dict[key] != nil

Hope it work for you. Thanks

希望对你有用。谢谢

#5


0  

This works for me [Swift 3.0]:

这适合我[Swift 3.0]:

let myVar = "c"
let myDict: [String: Int] = ["a": 0, "b": 1, "c": 2]
if myDict.keys.contains(myVar) {
   print(myVar)
} else {
   print("ERROR")
}

#6


-1  

I handled it this way in Swift 4:

我很快就做到了:

extension Dictionary {
    func contains(key: Key) -> Bool {
        let value = self.contains { (k,_) -> Bool in key == k }
        return value
    }
}

This uses Dictionary.contains(where: (key: Hashable, value: Value) throws -> Bool). By encapsulating it as an extension I have a good shot at updating the implementation to something better without modifying my code. I'm avoiding creating data, which index(forKey:Key) does. I'm hoping it's more efficient than accessing keys since that must create the whole array before searching it.

它使用字典。包含(其中:(键:Hashable, value: value)抛出-> Bool)。通过将它封装为一个扩展,我可以很好地将实现更新为更好的东西,而无需修改代码。我避免创建索引(forKey:Key)所做的数据。我希望它比访问键更高效,因为在搜索它之前必须创建整个数组。

#1


59  

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:

实际上,您的测试字典[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

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

要区分“关键不在词典中”和“关键的值是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")
}

#2


29  

I believe the Dictionary type's indexForKey(key: Key) is what you're looking for. It returns the index for a given key, but more importantly for your proposes, it returns nil if it can't find the specified key in the dictionary.

我相信字典类型的indexForKey(key: key)就是你要找的。它返回给定键的索引,但更重要的是对于您的提议,如果在字典中找不到指定键,它将返回nil。

if dictionary.indexForKey("someKey") != nil {
    // the key exists in the dictionary
}

Swift 3 syntax....

斯威夫特3语法....

if dictionary.index(forKey: "someKey") == nil {
    print("the key 'someKey' is NOT in the dictionary")
}

#3


2  

You can always do:

你可以做的:

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

}
else {
}

However I really dislike the idea of creating an NSDictionary which can contain optionals.

然而,我真的不喜欢创建一个包含optionals的NSDictionary。

#4


1  

Try this:

试试这个:

let value = dict[key] != nil

Hope it work for you. Thanks

希望对你有用。谢谢

#5


0  

This works for me [Swift 3.0]:

这适合我[Swift 3.0]:

let myVar = "c"
let myDict: [String: Int] = ["a": 0, "b": 1, "c": 2]
if myDict.keys.contains(myVar) {
   print(myVar)
} else {
   print("ERROR")
}

#6


-1  

I handled it this way in Swift 4:

我很快就做到了:

extension Dictionary {
    func contains(key: Key) -> Bool {
        let value = self.contains { (k,_) -> Bool in key == k }
        return value
    }
}

This uses Dictionary.contains(where: (key: Hashable, value: Value) throws -> Bool). By encapsulating it as an extension I have a good shot at updating the implementation to something better without modifying my code. I'm avoiding creating data, which index(forKey:Key) does. I'm hoping it's more efficient than accessing keys since that must create the whole array before searching it.

它使用字典。包含(其中:(键:Hashable, value: value)抛出-> Bool)。通过将它封装为一个扩展,我可以很好地将实现更新为更好的东西,而无需修改代码。我避免创建索引(forKey:Key)所做的数据。我希望它比访问键更高效,因为在搜索它之前必须创建整个数组。