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
As suggested here and above, the best solution is to use Dictionary.index(forKey:) which returns Dictionary. Regardless of whether your value is an optional type, this returns an optional index, which if nil, definitively tells you whether the key exists in the dictionary or not. This is much more efficient than using Dictionary.contains(where:) which is documented to have "complexity O(n), where n is the length of the sequence."
So, a much better way to write .containsKey() would be:
extension Dictionary {
func contains(key: Key) -> Bool {
self.index(forKey: key) != nil
}
}
I've been advised that dict.keys.contains() is actually O(1), so feel free to use it if you prefer.