๐ŸŽ“ A1Learner
๐Ÿ”

Swift Dictionary Iteration

Dictionary iteration is visiting the entries of a dictionary one at a time. A loop can read each key and each value in turn.

Sorted keys, looked-up values

The loop walks the keys in sorted order. Each key prints beside its looked-up value.

let scores: [String: Int] = ["Ben": 75, "Ana": 90, "Cid": 60]
for key in scores.keys.sorted() {
    print(key, scores[key] ?? 0)
}

Summing every value

This loop visits each pair directly and adds its value. The final total does not depend on visit order.

let scores: [String: Int] = ["Ben": 75, "Ana": 90]
var total = 0
for pair in scores {
    total += pair.value
}
print(total)

Counting keys and values

Three entries give three keys and three values. Both counts print 3.

let scores: [String: Int] = ["Ana": 90, "Ben": 75, "Cid": 60]
print(scores.keys.count)
print(scores.values.count)

Example

let prices: [String: Int] = ["pen": 3, "book": 12, "ruler": 5]
for key in prices.keys.sorted() {
    print(key, prices[key] ?? 0)
}
var total = 0
for pair in prices {
    total += pair.value
}
print(total)
print(prices.keys.count)

Key points

  • The keys view holds every key in a dictionary.
  • Sorting the keys gives the loop a fixed, readable order.
  • Each sorted key can look its own value back up.
  • A direct loop over a dictionary hands over one key and value pair per turn.
  • A total built inside a loop stays the same in any visit order.
  • The keys count and the values count both match the entry count.

In this example, the first line builds a price dictionary with pen, book, and ruler. The sorted loop prints book with 12 first, then pen with 3, then ruler with 5. The second loop adds every value into a total. The next line prints that total, 20. The last line prints the key count, 3.

Note

A dictionary keeps no fixed order for its entries, so sorted keys are the safe route for printed lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

Why does the sorted-keys loop print its lines in the same order on every run?