Iterating Over Dictionaries

You can iterate over a dictionary much the same way that you iterate over an array—by using a for-in loop. The only difference between an array for-in loop and a dictionary for-in loop is that with the dictionary loop, you are able to get both keys and values while looping, like this:

for (ssn,name) in people {    println("SSN: \(ssn) Name: \(name)")}// SSN: 198364775 Name: Francis Green// SSN: 176354888 Name: Trevor Kalan// SSN: 186574663 Name: John Smith

You can also loop through just the keys of a dictionary, with .keys. In addition, you can loop though just the values with .values:

for ssn in people.keys {    println("SSN: \(ssn)")}for name in people.values ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.