Skip to content

Swift Dictionary API

Swift's Dictionary<K, V> — a collection of unique keys mapped to values, with O(1) average lookup.

1 class · 7 methods

Dictionary

7 methods

A 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 pair
Dictionary.count -> Int

The number of key-value pairs in the dictionary.

Returns

Int

Example

swift
let d = ["a": 1, "b": 2, "c": 3]
print(d.count)  // 3
Dictionary.keys -> Dictionary.Keys

A 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.Values

A 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

NameTypeDescription
valueValueNew value to set.
keyKeyKey to update.

Returns

Value?

Example

swift
var d = ["a": 1, "b": 2]
let old = d.updateValue(10, forKey: "a")
// old == 1, d["a"] == 10
Dictionary.removeValue(forKey: Key) -> Value?

Removes the given key and its associated value, returning the removed value (or nil).

Parameters

NameTypeDescription
forKeyKeyKey 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) rethrows

Calls the given closure on each key-value pair in the dictionary.

Parameters

NameTypeDescription
body((key: Key, value: Value)) -> VoidClosure 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