O'Reilly logo

Application Development with Swift by Hossam Ghareeb

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

Dictionaries

Dictionaries in Swift are like arrays in special characteristics, such as mutable and strongly typed. Dictionary is mutable by default, except if used with let. Also keys and values should be of the same type.

The dictionary type is inferred by the initial values, or you can explicitly write it using the square brackets [keyType, valueType].

Initializing a dictionary

To initialize a dictionary, you have two options. The first option is to create an empty one with no data. You can create it like this:

var dic1 = [String:Int]() // 0 key/value pairs

As we see in this case, we had to explicitly write the type of keys and values.

In the second option, you have the predefined values like this:

var dic2 = ["EN" : "English", "FR" : "French"] //["EN": ...

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