Loop Through a Dictionary in Swift

We can use a simple for loop to iterate over a dictionary in Swift and access each key-value pair. Below is a very simple Swift code example that demonstrates how to create a new dictionary with default values and then loop through a dictionary and print out key-value pairs.

Create a New Dictionary

//Create Dictionary
var myDictionary = ["firstName": "Sergey", "lastName": "Kargopolov", "email":"[email protected]"]

Loop Through Dictionary

for (key,value) in myDictionary {
    print("\(key) = \(value)")
}

Below is a screenshot of how the above code snippet looks and works in the Xcode Playground.

Loop through a dictionary in Swift

And this is it! I hope this short Swift tutorial was helpful to you. Have a look through other Swift tutorials on this web site and hopefully, you will find more to learn.

Leave a Reply

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