Dictionary

A dictionary is collection of key-value pairs.

var dic = [String: String]() 
dic["firstName"]="Harry" // add pair ["firstName" : "Harry"]
print("name \(dic["firstName"])") // get value by key
dic["firstName"]=nil // remove pair with key "firstName"

// convert to arrays
let dicKeys = [Int](responseMessages.keys) // array of keys
let dicValues = [String](responseMessages.values) // array of values

Swift supports a dictionary literals. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets.

var emptyDict: [String: String] = [:]
var responseMessages = [200: "OK",
                        403: "Access forbidden",
                        404: "File not found",
                        500: "Internal server error"]

You can iterate over dictionary using for-in loop. Additionally you can iterate over keys or values.

for (k, v) in dic {
    print("'\(k)' : '\(v)'.")
}

for key in dic.keys {
    // ...
}

for key in dic.values {
    // ...
}

You can filter dictionary using filter method that returns new dictionary (Swift 4+).

let data = ["a": 0, "b": 42]
let filtered = data.filter { $0.value > 10 }
print(filtered) // ["b": 42]

Dictionary and NSDictionary

Bridging from Dictionary to NSDictionary always takes O(1) time and space. When the dictionary’s Key and Value types are neither classes nor @objc protocols, any required bridging of elements occurs at the first access of each element. For this reason, the first operation that uses the contents of the dictionary may take O(n).

Bridging from NSDictionary to Dictionary first calls the copy(with:) method (- copyWithZone: in Objective-C) on the dictionary to get an immutable copy and then performs additional Swift bookkeeping work that takes O(1) time. For instances of NSDictionary that are already immutable, copy(with:) usually returns the same dictionary in O(1) time; otherwise, the copying performance is unspecified. The instances of NSDictionary and Dictionary share buffer using the same copy-on-write optimization that is used when two instances of Dictionary share buffer.