Swift Dictionary contains()

The contains() method checks whether the specified key or value is present in the dictionary or not.

Example

var information = ["Sam": 1995, "Keane": 1980, "Hen": 2003]

// check if "Hen" is present as key or not var result = information.contains { $0.key == "Hen" }
print(result) // Output: true

contains() Syntax

The syntax of the dictionary contains() method is:

dictionary.contains{check}

Here, dictionary is an object of the Dictionary class.


contains() Parameters

The contains() method takes a single parameter:

  • check - a closure that checks if the key or the value is present in dictionary or not.

contains() Return Values

The contains() method returns:

  • true - if the dictionary contains the specified key or value
  • false - if the dictionary doesn't contain the specified key or value

Example 1: Swift Dictionary contains()

var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]

//  check if "Harvey" is present as key or not
var result1 = information.contains { $0.key == "Harvey" }
print(result1) // check if 34 is present as value or not
var result2 = information.contains { $0.value == 34 }
print(result2) // check if "harvey" is present as key or not
var result3 = information.contains { $0.key == "harvey" }
print(result3)

Output

true
true
false

In the above program, notice the closure definition,

{ $0.key == "Harvey" }

This is a short-hand closure that checks whether the dictionary has "Harvey" key or not.

$0 is the shortcut to mean the first parameter passed into the closure.

The other two closure definitions are also short-hand closures that check whether the key or value is present or not.

Here,

  • "Harvey" is present as the key in information, so the method returns true.
  • "34" is present as the value for the "Donna" key, so the method returns true.
  • "harvey" is not present in information, so the method returns false.

Example 2: Using contains() With if...else

var information = ["Sam": 1995, "Keane": 1980, "Hen": 2003]

var result = information.contains { $0.key == "Hen" }

if result {
    print("Key is present")
}
else {
    print("Key is not present")
}

Output

Key is present
Did you find this article helpful?