Retrieve value from a dictionary in Swift

Working with a dictionary often requires good hands-on on the topic and it is no doubt that fetching value associated with the key is important in the dictionary. This tutorial is all about working with the values in the dictionary, particularly how to fetch the values in a dictionary.

Retrieve all the values from a dictionary using a for-in loop

This method iterates over the dictionary and fetches all the values from it necessarily not in the same order. This method works as-

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

Output-

24
5
8

Fetching dictionary value with their index in Swift

Sometimes, we need to fetch the values with their index, but again the order is not preserved in the dictionary, every time you run the program, the order might change. To fetch values from a dictionary with their indices-

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

Here we have created an enumerated list of fruits which is nothing but a sequence of key-value pairs then we used the key element’s value and printed it at the output screen as-

0:24
1:5
2:8

Fetch value from a dictionary using key

This is the most frequently required/used task when we study dictionaries and it is much more useful too. We can do it very easily as-

var fruits=["Apple":5,"Banana":24,"Custard Apple":8]
var quantity=fruits["Apple"]
print("\(quantity)")

Output-

Optional(5)

Here we have worked on a dictionary and we have fetched values associated with the key-apple and the result shows 5.

This tutorial is about fetching/retrieving/accessing the value from a dictionary. Here are 3 methods devised where we have 2 consisting of fetching all the values whereas the last one is about fetching the value associated with a particular key. Thanks for reading! I hope you found this tutorial helpful.

Also read: Retrieve key from a dictionary in Swift

Leave a Reply

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