iterate over a dictionary in swift

To iterate over a dictionary in Swift, you can use a for-in loop with the Dictionary type's keys and values properties, as well as its enumerated() method for accessing key-value pairs with their respective index.

Here is an example code snippet:

main.swift
let grades = ["Alice": 90, "Bob": 85, "Charlie": 92]

// iterating over keys
for student in grades.keys {
    print(student)
}

// iterating over values
for grade in grades.values {
    print(grade)
}

// iterating over key-value pairs with index
for (index, pair) in grades.enumerated() {
    print("Student at index \(index) is \(pair.key) with grade \(pair.value)")
}
371 chars
17 lines

This would output:

main.swift
Alice
Bob
Charlie
90
85
92
Student at index 0 is Alice with grade 90
Student at index 1 is Bob with grade 85
Student at index 2 is Charlie with grade 92
153 chars
10 lines

gistlibby LogSnag