Dictionaries
Dictionary[K, V] is a hash map: an unordered collection of key-value pairs where each key appears at most once. Keys must conform to Hashable.
Creating
let ages: Dictionary[String, Int] = ["alice": 30, "bob": 27];
let empty: Dictionary[String, Int] = [:];
Literal syntax [k: v, ...] mirrors the array literal but with : between key and value. An empty literal is [:].
Lookup
Indexing returns Optional[V] — keys might not exist:
let ages: Dictionary[String, Int] = ["alice": 30, "bob": 27];
let alice = ages("alice"); // .Some(30)
let mallory = ages("mallory"); // .None
if let .Some(age) = ages("alice") {
println("alice is \(age)");
}
For a default if missing, use unwrap(or:) on the result, or the default: subscript:
let ages: Dictionary[String, Int] = ["alice": 30, "bob": 27];
let bobAge = ages("bob").unwrap(or: 0);
let zedAge = ages("zed", default: 0); // 0; the default is not stored
Inserting and updating
insert handles both insert and update — it returns the previous value as an Optional, so you can tell which one happened:
var scores: Dictionary[String, Int] = [:];
scores.insert("alice", 99); // insert; returns .None
scores.insert("alice", 100); // update; returns .Some(99)
scores.remove("alice"); // returns the removed value as Optional
The subscript works for writing too. The plain subscript is Optional-typed on both sides: assigning .Some(v) inserts or updates, and assigning null removes the key. The unwrap: variant assigns the value directly:
var scores: Dictionary[String, Int] = [:];
scores(unwrap: "alice") = 99; // insert or update, no Optional wrapping
scores("alice") = .Some(100); // same, through the Optional subscript
scores("alice") = null; // removes the key
The dict must be var for any of these to work.
Iteration
A for loop yields key-value pairs:
let scores: Dictionary[String, Int] = ["alice": 99, "bob": 7];
for (name, score) in scores {
println("\(name): \(score)");
}
Iteration order is unspecified — don't rely on it. If you need order, sort the keys explicitly.
Common methods
let scores: Dictionary[String, Int] = ["alice": 99, "bob": 7];
scores.count;
scores.isEmpty;
scores.contains("alice"); // Bool; does the key exist?
scores.keys; // view over keys
scores.values; // view over values
The iterator chain works on the values:
let scores: Dictionary[String, Int] = ["alice": 99, "bob": 7];
let total = scores.values.iter().fold(from: 0, by: { (acc, v) in acc + v });