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"
//Adding a new value to an existing Dictionary
greetings["Australian"] = "G'day"
//Modifying an existing Dictionary value
greetings["English"] = "Hello"
/* 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"
//removing value by setting existing key to nil
greetings["Spanish"] = nil
//removing value using the removeValueForKey method
greetings.removeValueForKey("Spanish")
//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 a Dictionary to return both Key and Value:
for (language,greeting) in greetings {
println("The greeting in \(language) is \(greeting)")
}