swift dictionary contains key code example

Example 1: swift 5 check if dictionary contains key

if let key = self.dictionary["key"] {
	print(key) // returns value
}

// OR
extension Dictionary {
  func contains(key: Key) -> Bool {
    self.index(forKey: key) != nil
  }
}

Example 2: swift dictionary contains key

if let value = self.dictionary["key"] {
	print(value) // prints value
}

// OR
extension Dictionary {
  func contains(key: Key) -> Bool {
    self[key] != nil
  }
}