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 th
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.