Retrieve key from a dictionary in Swift

When working on a dictionary, mostly we work on its value but sometimes we are required to fetch the key’s value, this tutorial is all about learning different and easy methods to fetch the key in a dictionary. A dictionary consists of a key-value pair, the key with a corresponding value. For example, we need to save any item with its quantity, so we will create a dictionary for this purpose.

Fetch all the keys  from a dictionary using a for-in loop

This method is the easiest of all which iterates over the dictionary and fetches all the keys present. A for-in loop in Swift is used to do this task and it fetches all the keys present in a dictionary as-

var fruits=["Apple":5,"Banana":24,"Custard Apple":8]
for (key,value) in fruits{
    print("\(key)")
}

Output:

Banana
Apple
Custard Apple

A dictionary is never ordered, it is no guarantee that the way you entered data will be the same when you fetch the data. Here also, you can observe that the order was not preserved.

Fetch all the keys with their index

This method describes how to print all the keys with the index values. For this, we just need to follow the above steps along with creating an enumerated list of fruits which is a sequence of key-value pairs. Here’s the implementation-

for key in fruits.enumerated(){
    print("\(key.offset):\(key.element.key)")
}

Output-

0:Apple
1:Banana
2:Custard Apple

So we have printed the key with the index value. Again the dictionary does not preserve order, so your output may vary.

Fetch a particular key using its corresponding value in Swift

We can easily fetch any particular value from its key, but to fetch the key from its value requires an extension in Swift which will contain a function to check for the value and returns the key if values are matched. As we can see in the below code there is an extension for Dictionary where we are comparing the value to equitable, Equitable is a protocol that is used to compare values using the “==” operator. A function is created using the name findingKey which will compare the second element($1) to the value passed and will return the key value. We will print the output and check for the results

var fruits=["Apple":5,"Banana":24,"Custard Apple":8]
extension Dictionary where Value:Equatable{
    func findingKey(forValue val:Value)->Key?{
        return first(where:{$1==val})?.key
    }
}
print(fruits.findingKey(forValue:8))

Output-

Custard Apple

We have covered overall 3 different methods to fetch keys from a dictionary in Swift. Thanks for reading, I hope you found this tutorial helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *