Introduction to Swift: Dictionaries

A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. In this tutorial we will look at some common functions in Swift applied on dictionaries. To follow this tutorial you will need Xcode 6 and start a playground file. Xcode 6 can be downloaded from Apple's developer portal. 

Update: In Xcode Beta 3 Swift introduced a new Dictionary type signature syntax. This tutorial is updated to reflect this changes.

Empty Dictionary

To declare an empty dictionary you will need to explicit declare the type of the key/value pair.

var emptyDictionary = Dictionary<String, String>()
// or
var emptyDictionary = [String: String]()

Declaring Dictonaries

Dictionary can be declared with inferred types or the key-value types can be explicit declared.

// Inferred
var personAge = ["Larry King": 43, "Mike Johnson":32, "Ted Brown": 67]

// Explicit
var personAgeExplicit:Dictionary<String, Int> = ["Larry King": 43, "Mike Johnson":32, "Ted Brown": 67]
// or
var personAgeExplicit:[String: Int] = ["Larry King": 43, "Mike Johnson":32, "Ted Brown": 67]

Modifying Dictionaries

The most common operations to modify a dictionary are insert, update and delete a key-value pair.

// Insert
personAge["Kevin Bird"] = 21

// Update
personAge["Mike Johnson"] = 33

// Delete
personAge["Ted Brown"] = nil
// or
personAge.removeValueForKey("Ted Brown")

Accessing Dictionaries

to access a value in a dictionary the key can be requested using subscripts. Note when a value is requested the returned type is a optional because the key may not exists.

let optionalAge = personAge["Larry King"]

if let age = optionalAge {
    println("Larry King is \(age) years old.")
} else {
    println("Can't find Larry King")

This finished this part of the introduction serie of Swift programming