Swift Program to Search an Element in a Dictionary


In a Swift dictionary, we can search for an element that is either a key or value with the help of contains() function. The contains() function will return a boolean value which represents whether the specified element(key or value) is found or not.

Syntax

dict.contains{$0.key == “KeyName”}

Here, dict is the dictionary. The contains() function returns a boolean value which represents the result. Here we pass a closure in the function which will check if the current key is equal to the specified key or not and then return the result accordingly.

Algorithm

  • Step 1 − Create a dictionary with key-value pairs.

  • Step 2 − Create a variable to store the result.

  • Step 3 − Then use contains() function to check if the specified key is present in the given dictionary or not.

  • Step 4 − Display the output.

Example

In the following Swift program, we are going to search for an element in a dictionary. So for that, we create a dictionary with key-value pairs and then we use contains() method to check if the given key is present in the dictionary or not, for that, we pass a closure in the function which compares all the keys with the specified key and return boolean result.

import Foundation
import Glibc

var myCityRank:[String:Int] = ["Delhi": 31, "Goa": 3, "Pune": 1, "Jaipur": 2, "Kolkata": 87]

var result = myCityRank.contains{$0.key == "Goa"}

if (result == true) {
   print("Congratulations! Key is found")
} else {
   print("Key does not found. Please try again!")
}

Output

Congratulations! Key is found

Conclusion

So this is how we can search for an element in a dictionary. Using contains method we can search key or value. We can also do the same thing using [] bracket notation. But the most effective method is the contains() method.

Updated on: 09-May-2023

808 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements