Dictionaries in Swift​

Become a Subscriber

** Note: Video is part of a Swift beginner series by MadApper (a.k.a. Paul Napier)**

The second collection type in Swift is called a dictionary. Dictionaries are useful when you need to access a variable by name or another identifier. A dictionary is a container that stores multiple values of the same type. Dictionaries have keys, which act as identifiers for the value within a dictionary. Let’s look at an example dictionary variable

var dict:Dictionary = Dictionary<String, String>()

We have declared a variable called dict. Its type is explicitly Dictionary. Dict is equal to Dictionary, meaning a dictionary whose keys are of type String and whose values are of type String. The parentheses are shorthand for an empty dictionary.

We can declare a dictionary containing objects implicitly by using square brackets.

var dict2 = ["key1":"value1","key2":"value2"]

Like arrays, if we implicitly declare a dictionary and use more than one type in the object key or values, Swift creates an NSDictionary.

var dict2 = ["key1":10,"key2":"value2"]

//this is of type NSDictionary, not Dictionary
var dict2: Dictionary<String, String> = ["key1":"value1","key2":"value2"]

//this is an explicit dictionary declaration

Once again, be explicit as much as possible.

To access a dictionary element, we put the key whose value we want to access in square brackets.

dict2["key2"] //returns [some "value2"]