June 11th   2014

Dictionary collection

  iOS , Swift

A dictionary stores unordered pairs values - each pair of the same type.

Back in Objective-C we had 3 types of collections:

  • NSArray - an ordered collection
  • NSDictionary - a key mapped collection
  • NSSet - a collection of unique objects

Swift provides only the first two collection types: arrays and dictionaries.

Dictionary

A dictionary stores unordered pairs values - each pair of the same type. The major difference here is the requirement for the pair of values must be of the same type. Here is an example:

let population = ["UK": 63_230_000, "France": 65_700_000, "Spain": 47_270_000]

Trying to add elements of different types will result in a compiler error:

let population = ["UK": 63_230_000, "France": 65_700_000, "Spain": 47_270_000, "Italy" : "almost as many as UK"]

Modifying dictionaries

Adding new pairs to a dictionary is trivial. First, we'll define population as a variable and then add a new element to it:

var population = ["UK": 63_230_000, "France": 65_700_000, "Spain": 47_270_000] population["Italy"] = 60_920_000

population now contains:

"UK": 63230000
"France": 65700000
"Spain": 47270000
"Italy": 60920000

Dictionary Type

As you probably noticed, we didn't have to specify the type of elements the dictionary will store. This is because the compiler can infer the type from the value passed on the first assignment. However, there are instances when the initial value is either not known or not available. We'll therefore need to specify the dictionary type:

var population: Dictionary<String, Double>

We're defined a variable population that stores pair of elements, the key being a string and the value a Double.

population is defined, it is not ready to use - one will get an error if trying to use it:

var population: Dictionary<String, Double>
population["Italy"] = 60_920_000
error: variable 'population' used before being initialized

We'll need to assign a value to it before being able to use it:

var population: Dictionary<String, Double>
population = ["UK": 63_230_000]
population["Italy"] = 60_920_000

population now contains:

"UK": 63230000
"Italy": 60920000

Useful Dictionary methods

var population = ["UK": 63_230_000, "France": 65_700_000, "Spain": 47_270_000]

population.count                    // 3

population.keys                     // collection of dictionary keys
population.value                    // collection of dictionary values

population["UK"] = nil                    // remove the pair with key "UK"
population.removeAll(keepCapacity: true)  // removes all pairs

Iterate through a dictionary

var population = ["UK": 63_230_000, "France": 65_700_000, "Spain": 47_270_000]

for a_key in population.keys {
    println("key: \(a_key)   value: \(population[a_key])")
}

This will output:

key: France   value: 65700000
key: UK       value: 63230000
key: Spain    value: 47270000

«         »

Web Analytics