Swift – Iterate through Dictionary
Welcome to Swift Tutorial. In this tutorial, we will learn how to iterate through (key, value) pairs of Dictionary in Swift and print them.
To iterate over (key, value) pairs of a Dictionary, use for loop. You can also access the index of the (key, value) paris using the enumerated Dictionaries.
Example 1 – Iterate over Dictionary in Swift
In this example, we shall create a dictionary, and print them by iterating over the (key, value) pairs.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (key, value) in myDictionary {
print("(\(key),\(value))")
}
Output
(Raghu,82)
(John,79)
(Mohan,75)
Example 2 – Iterate over Dictionary in Swift
In this example, we shall create a dictionary with initial values, and print them by iterating over the (key, value) pairs of the enumerated dictionary.
main.swift
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (index, key_value) in myDictionary.enumerated() {
print("\(index): \(key_value)")
}
Output
0: (key: "John", value: 79)
1: (key: "Mohan", value: 75)
2: (key: "Raghu", value: 82)
In this example, we have used Dictionary.enumerated()
. Using this method, we can access the index of the (key, value) pair as first argument and (key, value) pair itself as the second argument.
If you do not intend to use the index, you may remove the variable name, index, from the for loop or replace it with an underscore.
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (_, key_value) in myDictionary.enumerated() {
print("\(key_value)")
}
or
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
for (key_value) in myDictionary.enumerated() {
print("\(key_value)")
}
Conclusion
In this Swift Tutorial, we have learned to iterate over a Dictionary in Swift with the help of example programs.