Swift - Data Type Dictionaries

Introduction

A dictionary is an unordered collection that is indexed by keys.

You create a dictionary using the square bracket syntax.

You could use a dictionary like this:

var crew = ["A": "value a", 
            "B": "value b", 
            "C": "value c"] 

To access its contents you use the subscript operator.

You pass in the key of the element you are after.

For example, to get the "C" value, you do this:

crew["C"] // "value c" 

You can add new elements by giving them a key in the dictionary:

crew["D"] = "d value" 
crew["S"] = "s value" 

To remove elements:

crew.removeValue(forKey: "S") 

If you ask for a key that doesn't exist, a dictionary will return nil.

If you set an existing value to nil this has the same effect as removing that element from the dictionary:

crew["S"] = "s value" 
crew["S"] = nil 
crew["S"] // nil 

nil is a special case in Swift that is "nothing."

Dictionaries can contain almost any values and be indexed by almost any key type.

For example, you can make a dictionary use Int values for both keys and values:

let arrayDictionary = [0:1, 
                       1:2, 
                       2:3, 
                       3:4, 
                       4:5] 
arrayDictionary[0] // 1 

Related Topics

Exercise