Dictionary
7 methodsA collection whose elements are key-value pairs. A value type bridged to NSDictionary.
Dictionary subscript [Key] -> Value?Accesses the value associated with the given key, returning nil if the key is not present.
Returns
Value?
Example
swift
var d: [String: Int] = ["a": 1, "b": 2]
print(d["a"]!) // 1
print(d["c"]) // nil
d["c"] = 3 // inserts new pairDictionary.count -> IntThe number of key-value pairs in the dictionary.
Returns
Int
Example
swift
let d = ["a": 1, "b": 2, "c": 3]
print(d.count) // 3Dictionary.keys -> Dictionary.KeysA collection containing just the keys of the dictionary.
Returns
Dictionary.Keys
Example
swift
let d = ["a": 1, "b": 2]
let keys = Array(d.keys)
// keys == ["a", "b"] (order may vary)Dictionary.values -> Dictionary.ValuesA collection containing just the values of the dictionary.
Returns
Dictionary.Values
Example
swift
let d = ["a": 1, "b": 2]
let values = Array(d.values)
// values == [1, 2] (order may vary)Dictionary.updateValue(_ value: Value, forKey key: Key) -> Value?Updates the value for the given key, returning the old value (or nil if key was new).
Parameters
| Name | Type | Description |
|---|---|---|
| value | Value | New value to set. |
| key | Key | Key to update. |
Returns
Value?
Example
swift
var d = ["a": 1, "b": 2]
let old = d.updateValue(10, forKey: "a")
// old == 1, d["a"] == 10Dictionary.removeValue(forKey: Key) -> Value?Removes the given key and its associated value, returning the removed value (or nil).
Parameters
| Name | Type | Description |
|---|---|---|
| forKey | Key | Key to remove. |
Returns
Value?
Example
swift
var d = ["a": 1, "b": 2]
let removed = d.removeValue(forKey: "a")
// removed == 1, d == ["b": 2]Dictionary.forEach(_ body: ((key: Key, value: Value)) throws -> Void) rethrowsCalls the given closure on each key-value pair in the dictionary.
Parameters
| Name | Type | Description |
|---|---|---|
| body | ((key: Key, value: Value)) -> Void | Closure applied to each pair. |
Returns
Void
Example
swift
let d = ["a": 1, "b": 2]
d.forEach { (k, v) in
print("\(k)=\(v)")
}
// prints:
// a=1
// b=2