Iterating over a dictionary in Swift: how to loop through all keys and values
Hello! I recently started learning Swift and encountered a problem when working with dictionaries. I have a dictionary that stores student names and their grades:
```swift
var studentGrades: [String: Int] = [
"Anna": 85,
"Boris": 92,
"Victor": 78,
"Galina": 95
]
```
I want to display all students and their grades in the format "Name: grade". I tried using a for-in loop, but I don't understand how to properly access each element.
Here's what I tried:
```swift
for student in studentGrades {
print(student)
}
```
This outputs something strange like `(key: "Anna", value: 85)`. I need it to simply output "Anna: 85".
Also I want to:
1. Iterate only over keys (student names).
2. Iterate only over values (grades).
No answers yet.
Log in to leave an answer
Blogs