Adding and Removing Values

Now that you have seen how to update a value, let’s look at how you can update the key-value pairs in your dictionary by adding or removing a value. Begin by adding a value.

Listing 10.6  Adding a value

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: "Donnie Darko")
if let lastRating = oldRating {
     print(lastRating)
}
movieRatings["The Cabinet of Dr. Caligari"] = 5

Here, you add a new key-value pair to your dictionary using this syntax: movieRatings["The Cabinet ...

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.