Swift – Iterate over Dictionary Keys

To iterate over keys of a dictionary, we use for loop and iterate over the iterator returned by keys property of this Dictionary.

Refer Swift For Loop tutorial.

Example

In this example, we will create a Swift Dictionary with some initial values and print all the keys of the Dictionary.

main.swift

var myDictionary: [String:Int] = ["apple":75, "banana":82, "cherry":79]

for key in myDictionary.keys {
   print("\(key)")
}

Output

apple
cherry
banana
Program ended with exit code: 0

In this example, myDictionary.keys returns an array with all the keys in it. And we used a for loop to iterate over the keys String array.

ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to iterate over keys of a Dictionary using Dictionary.keys.