Check if key exists in dictionary of type [Type:Type?]

后端 未结 6 1804
时光说笑
时光说笑 2020-12-03 09:48

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

6条回答
  •  不知归路
    2020-12-03 10:11

    As suggested here and above, the best solution is to use Dictionary.index(forKey:) which returns Dictionary.Index?. 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.

提交回复
热议问题