The contains() method checks whether the specified key or value is present in the dictionary or not.
Example
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()
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 returnstrue."34"is present as the value for the"Donna"key, so the method returnstrue."harvey"is not present in information, so the method returnsfalse.
Example 2: Using contains() With if...else
Output
Key is present