Dictionaries

Dictionary objects look like this:

let myDict = ["One":"Eins", "Two":"Zwei", "Three":"Drei"] 

They are how Swift stores key-value pairs. A value is set and retrieved by using its key instead of an index, as one would with an array. Each key can occur only once in any particular Dictionary.

They're called Dictionary in Swift, but they're called map in Clojure, and object in JavaScript. That's not helped by the fact that both map and object are used in Swift, but have rather different meanings. Elsewhere, you may find dictionaries referred to as associative arrays or symbol tables. And yes, the first time I worked closely with a JavaScript programmer on a project, the conversation became a lot easier after we'd cleared that up.

Dictionary keys must be objects that conform to the Hashable protocol; these include String and Int objects.

Like the Array, Dictionary objects also come equipped with a pretty standard set of methods:

let count2 = myDict.count 
let uno = myDict["One"] // "Eins"

If the Dictionary does not contain a key-value pair with the required key, it returns nil:

let quattro = myDict["Four"] 

So, quattro will be nil.

We declare a mutable Dictionary with var:

var varDict = ["One": "Eins", "Two": "Zwei"] 

A key-value pair is added to and removed from a mutable Dictionary as follows:

varDict["Three"] = "Drei" 
varDict.removeValue(forKey: "One")

No prizes for guessing that values for existing keys are changed as follows:

varDict["One"] = "Een" 

We can declare a Dictionary object without initializing it, as follows:

var emptyDict1: [String: String] 
var emptyDict2: Dictionary<String, String>

These two methods are equivalent (the parallels with Array declarations are obvious). We declare and initialize an empty Dictionary with one of the following methods:

var emptyDict3 = [String: String]() 
var emptyDict4: [String: String] = [:]
var emptyDict5: Dictionary<String, String> = [:]

Once the type of Dictionary is clear:

var myDict = ["One": "Eins", "Two": "Zwei", "Three": "Drei"]  

(here, myDict is initialized as a Dictionary of type <String: String>), we can set it to the empty array with just the empty brackets:

myDict = [:] 

Don't forget the colon, though; it's not an Array.

If we declare a Dictionary object with let, we cannot change its values:

let constDict = ["One": "Eins", "Two": "Zwei"] 
constDict["One"] = "Un"

The second line will produce a compiler error.

You may find that it is frequently helpful to use a typealias to name a particular Dictionary type:

typealias memberRank = [String: Int]