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{



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(){

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-


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"]



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 *