Looping

You can use a for-in to loop through a dictionary. Swift’s Dictionary type provides a convenient mechanism to loop through an instance’s key-value pair for each entry. This mechanism breaks each entry into its constituent parts by providing temporary constants representing the key and the value. These constants are placed within a tuple that the for-in loop can access inside of its body.

Listing 10.9  Looping through your dictionary

import Cocoa var movieRatings = ["Donnie Darko": 4, "Chungking Express": 5, "Dark City": 4] print("I have rated \(movieRatings.count) movies.") let darkoRating = movieRatings["Donnie Darko"] movieRatings["Dark City"] = 5 movieRatings let oldRating: Int? = movieRatings.updateValue(5, forKey: ...

Get Swift Programming: The Big Nerd Ranch Guide 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.