Dictonaries: Taking Arrays to the next level

Syntax:

let greetings = [Key1 : Value1, Key2 : Value2, Key3 : Value3]

A Dictionary is an Array of Key:Value pairs. Each value in the Dictionary can be referenced by it's Key. The Key and Value types can be inferred by the values provided, or can be explicitly declared when the Dictionary is defined. All Keys must be of the same type, and all Values must be of the same type (if differing types are needed, perhaps a Tuple would be the right choice). Keys must be of a hashable type. Any of the basic types in Swift are hashable (String, Int, Double, Bool).

//Dictionary with type declared
let greetings: Dictionary<String,String> = ["English" : "Hi", "Hawaiian" : "Aloha", "Italian" : "Ciao"]

//Dictionary with type inferred
let greetings = ["English" : "Hi", "Hawaiian" : "Aloha", "Italian" : "Ciao"]

println("\(greetings["English"]) There")
//returns "Hi There"


Modifying Dictionaries: To modify a Dictionary you can add/modify values by specifying the Key for the Dictionary and assigning a value (also known as SubScript syntax)

//Adding a new value to an existing Dictionary
greetings["Australian"] = "G'day"

//Modifying an existing Dictionary value
greetings["English"] = "Hello"


Methods:

/* Updating a Dictionary value using updateValue(forKey:) method, and storing the previous value in a Constant */
let oldEnglishVal = greetings.updateValue("Howdy", forKey: "English")

println("The new English greeting is \(greetings["English"]), the previous value was \(oldEnglishValue)")
//prints "The new English greeting is Howdy, the previous value was Hello"


To remove values from a Dictionary you can either set an existing Key to nil, or use the removeValueForKey method

//removing value by setting existing key to nil
greetings["Spanish"] = nil

//removing value using the removeValueForKey method
greetings.removeValueForKey("Spanish")


Properties:

//retrieving the number of values in a Dictionary
println("There are \(greetings.count) values in the greetings Dictionary")
//prints "There are 4 values in the greetings Dictionary"

//retrieving all of the Keys in a Dictionary
for key in greetings.keys {
  println("Key: \(key)")
}

//retrieving all of the Values in a Dictionary
for val in greetings.values {
  println("Value: \(val)")
}


Iterating over Dictionaries: for-in loops can be used to iterate over Dictionaries

//iterating over a Dictionary to return both Key and Value:
for (language,greeting) in greetings {
  println("The greeting in \(language) is \(greeting)")
}