O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Immutable Dictionaries

Creating an immutable dictionary works much the same as creating an immutable array. You use the let keyword to tell the Swift compiler that you do not want your instance of Dictionary to change. Create an immutable dictionary that lists the track names of a short fictional album along with each track’s length in seconds.

Listing 10.11 Creating an immutable dictionary

...
let album = ["Diet Roast Beef": 268,
             "Dubba Dubbs Stubs His Toe": 467,
             "Smokey's Carpet Cleaning Service": 187,
             "Track 4": 221]

The track names are the keys and the track lengths are the values. If you try to change this dictionary, the compiler will give you an error and prevent the change. (Go ahead and try it!)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required