How to Iterate through a Dictionary in Swift
Use a for-in loop to iterate through the key-value pairs of a Swift Dictionary. Each element is available as a tuple, so you can destructure it directly into key and value.
To iterate over (key, value) pairs of a Dictionary, use for loop. You can also use enumerated() when you need a temporary offset for each element.
- A dictionary element is a
(key: Key, value: Value)tuple. - A Swift dictionary does not guarantee a fixed iteration order.
- The offset returned by
enumerated()is not a permanent dictionary index.
Iterate through Swift Dictionary Key-Value Pairs
In this example, we shall create a dictionary, and print its entries 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)
The output order may be different when you run the program. Dictionary iteration order is not guaranteed, so code should not depend on one specific sequence of entries.
Iterate through a Swift Dictionary with an Offset
In this example, we shall create a dictionary with initial values, and print its entries by iterating over 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, Dictionary.enumerated() returns a sequence of (offset, element) tuples. The first value is a zero-based offset for the current traversal. The second value is the dictionary element, which contains its key and value.
The offset is useful for display numbering, but it should not be treated as a stable dictionary index. Both the offset and the element order can change when the dictionary is rebuilt or modified.
If you do not intend to use the offset, you may 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)")
}
In the second form, key_value receives the complete value produced by enumerated(), including both the offset and the dictionary element. Use a direct dictionary loop when you need only the key and value.
Iterate through Only Dictionary Keys or Values in Swift
Use the keys view when only keys are required, or the values view when only values are required.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
for name in scores.keys {
print(name)
}
for score in scores.values {
print(score)
}
These views follow the dictionary’s current iteration order, which is still not guaranteed to be sorted.
Iterate through a Swift Dictionary in Sorted Key Order
Sort the keys before iteration when the output must be predictable, such as for a report, test, menu, or user interface.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
for key in scores.keys.sorted() {
if let value = scores[key] {
print("\(key): \(value)")
}
}
Output
John: 79
Mohan: 75
Raghu: 82
You may also sort the dictionary entries by value. Because sorted(by:) returns an array of key-value tuples, the resulting sequence has a defined order for that operation.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
for (name, score) in scores.sorted(by: { $0.value > $1.value }) {
print("\(name): \(score)")
}
Use forEach with a Swift Dictionary
A dictionary also supports forEach. Its closure receives one dictionary element at a time.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
scores.forEach { key, value in
print("\(key): \(value)")
}
A regular for-in loop is usually clearer when you need break or continue. The forEach method does not support those loop-control statements in the same way.
Transform Swift Dictionary Entries with map
Use map when the goal is to create a new array from the dictionary rather than only perform an action for each entry.
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
let labels = scores.map { key, value in
"\(key) scored \(value)"
}
print(labels)
The returned array follows the dictionary’s iteration order unless you sort the entries before calling map.
Use a Swift Dictionary with SwiftUI ForEach
SwiftUI’s ForEach needs a collection with stable identities. A practical approach is to sort the dictionary keys and use each key as the identity.
import SwiftUI
struct ContentView: View {
let scores = ["Mohan": 75, "Raghu": 82, "John": 79]
var body: some View {
List {
ForEach(scores.keys.sorted(), id: \.self) { key in
if let score = scores[key] {
Text("\(key): \(score)")
}
}
}
}
}
This produces a consistent display order and gives each row a stable identifier as long as the dictionary keys are unique and stable.
Common Swift Dictionary Iteration Mistakes
- Expecting insertion order: Sort keys or entries whenever order matters.
- Treating an enumerated offset as a dictionary index: The offset belongs only to that traversal.
- Using map only for side effects: Use
for-inorforEachwhen no transformed array is needed. - Changing dictionary contents during traversal: Collect the keys to update first, then perform changes in a separate pass.
Swift Dictionary Iteration FAQs
How do I get both the key and value while looping through a Swift dictionary?
Use tuple destructuring in a for-in loop: for (key, value) in dictionary. The two variables receive the key and value of each entry.
Does a Swift dictionary preserve iteration order?
No fixed iteration order should be assumed. Sort the keys or key-value tuples before iterating when deterministic output is required.
What does enumerated() return for a Swift dictionary?
It returns a sequence of (offset, element) tuples. The element is the dictionary’s (key, value) tuple, while the offset is a temporary zero-based count for that traversal.
Should I use for-in or forEach for a Swift dictionary?
Use for-in for general iteration, especially when you need break or continue. Use forEach for a compact closure-based operation when loop control is unnecessary.
How do I iterate over a dictionary in SwiftUI ForEach?
Convert the dictionary into a stable ordered sequence, such as sorted keys, and provide a stable identifier. Then read each value from the dictionary using its key.
Swift Dictionary Iteration Review Checklist
- Confirm that examples do not imply a guaranteed dictionary order.
- Use
enumerated()only when a temporary traversal offset is required. - Sort keys or entries before presenting ordered output.
- Use
for-in,forEach, ormapaccording to whether the code loops, performs an action, or creates a transformed collection. - Give SwiftUI dictionary rows stable identities before using
ForEach.
Summary of Iterating through Swift Dictionaries
In this Swift Tutorial, we learned how to iterate through a Dictionary using for-in, enumerated(), keys, values, forEach, and map. We also sorted dictionary entries for predictable output and prepared dictionary data for SwiftUI ForEach.
TutorialKart.com