Swift Dictionaries
A Dictionary stores elements as key-value pairs, letting you find a value quickly by its key, independent of the number of elements.
Like arrays, it is avalue types, staying independent on assignment and when passed as an argument; but itdoesn't guarantee order, the opposite of arrays.
This article covers dictionary creation, adding/deleting/modifying entries, the default subscript, iteration, mapValues and merging, and the Hashable requirement for keys.
For elements stored by position, see 《Swift Arrays》。
Creating a dictionary
A dictionary's type is written with square brackets containing "key type: value type", for example [String: Int].
Literals are listed in the form key: value, and an empty dictionary has two ways to be written.
Example
import Foundation
// The type annotation for a dictionary literal is [key type: value type]
var ages
:
[
String
:
Int
]
=
[
"Runoob"
:
10
,
"RUNOOB"
:
5
]
// Empty dictionary, the two forms are equivalent
let empty
=
[
String
:
Int
]
(
)
var empty2
:
[
String
:
Int
]
=
[
:
]
(
ages.
count
, empty.
isEmpty
, empty2.
count
)
The output of the above code is:
2 true 0
The common creation methods are compared below.
| Syntax | Description |
|---|---|
| ["Runoob": 10, "RUNOOB": 5] | Literal, with key and value types inferred by the compiler |
| var ages: [String: Int] = [:] | Empty dictionary, using an empty literal plus a type annotation |
| String: Int | Call the type's initializer to get an empty dictionary |
| Dictionary(uniqueKeysWithValues:) | Created from a sequence of key-value pairs, keys must be unique |
Note:Written alone let empty = [:] It won't compile; the compiler can't infer the types of the key and value, so you must add a type annotation.
Adding, deleting, and modifying
Use subscript assignment to add or modify: if the key doesn't exist it's added, if it already exists it's overwritten.
Use removeValue(forKey:) to delete; it returns the removed value as an optional.
Example
import Foundation
var ages
:
[
String
:
Int
]
=
[
"Runoob"
:
10
,
"RUNOOB"
:
5
]
ages
[
"Swift"
]
=
11
// Key doesn't exist, add it
ages
[
"Runoob"
]
=
12
// Key already exists, overwrite it
(
ages.
count
)
// removeValue deletes and returns the removed value; returns nil when the key doesn't exist
let removed
=
ages.
removeValue
(
forKey
:
"RUNOOB"
)
(
removed
??
1
, ages.
count
)
// updateValue returns the old value that was replaced; returns nil when the key doesn't exist
if
let old
=
ages.
updateValue
(
20
, forKey
:
"Runoob"
)
{
(
"old value (old)"
)
}
(
ages
[
"Runoob"
]
??
0
)
The output of the above code is:
3
5 2
旧值 12
20
The differences among the three write methods are summarized below.
| Method | Purpose | Return Value |
|---|---|---|
| dict[key] = value | Add or overwrite | An assignment statement has no return value |
| updateValue(_:forKey:) | Add or overwrite | The replaced old value, nil when the key doesn't exist |
| removeValue(forKey:) | Delete by key | The deleted value, nil when the key doesn't exist |
| removeAll() | Clear the dictionary | None |
Subscript assignment returns Void and doesn't give you the old value; when you need to know "what it was before", use updateValue.
Note:The method name for deletion is removeValue(forKey:). In older tutorials, the removeValueForKey was renamed long ago and no longer compiles.
The default subscript
A regular subscript returns an optional, which must be unwrapped before use, making operations like counting and accumulating quite verbose.
A subscript with default directly provides a default value when the key doesn't exist, and allows in-place modification.
Example
import Foundation
var counts
=
[
"Runoob"
:
1
]
// When the key doesn't exist, first give the default value 0, then do += 1
counts
[
"RUNOOB"
,
default
:
0
]
=
1
counts
[
"RUNOOB"
,
default
:
0
]
=
1
(
counts
[
"RUNOOB"
]
??
0
)
(
counts.
count
)
The output of the above code is:
2
2
On the first execution, RUNOOB doesn't exist yet; the subscript expression first returns the default value 0, adds one, and writes it back to the dictionary, at which point the key is actually created.
On the second execution the key already exists, so it retrieves 1 and adds one to get 2.
Note:Without default , the subscript returns Int?, so writing directly counts["RUNOOB"] += 1 won't compile, because you can't add to an optional.
Iterate over a dictionary
A dictionary is aUnorderedcollection; iteration order isn't guaranteed, doesn't equal insertion order, and you definitely can't assume it's stable across versions or platforms.
When you need stable output, sort the keys first, then iterate.
Example
import Foundation
let ages
=
[
"Runoob"
:
10
,
"RUNOOB"
:
5
,
"Swift"
:
11
]
// Direct iteration retrieves all key-value pairs, but order isn't guaranteed; here we only sum the total
var total
=
0
for
(
_, value
)
in ages
{
total
=
value
}
(
total
)
// When stable order is needed, sort by key first
for
(
key, value
)
in ages.
sorted
(
by
:
{
$
0
.
key
<
$
1.
key
}
)
{
(
"(key): (value)"
)
}
(
ages.
keys
.
sorted
(
)
)
(
ages.
values
.
sorted
(
)
)
The output of the above code is:
26
RUNOOB: 5
Runoob: 10
Swift: 11
["RUNOOB", "Runoob", "Swift"]
[5, 10, 11]
Writing for (key, value) in ages directly gives an indeterminate order; the first code block above only accumulates a sum and doesn't depend on order, so the output is stable.
sorted(by:) converts the dictionary into an array of (key, value) arranged by the specified rule, so iteration becomes fixed.
keys and values return views, which themselves have no order guarantee, and usually need another layer of sorted() for use.
Note:Don't rely on the observed "insertion order". Dictionaries are stored internally with a hash table; element arrangement depends on hash values and current capacity, and may change after resizing.
mapValues and merging
mapValues only transforms values, leaves keys unchanged, and returns a new dictionary.
Example
import Foundation
let ages
=
[
"Runoob"
:
12
,
"Swift"
:
11
]
// mapValues only transforms values, preserving the original keys
let doubled
=
ages.
mapValues
{
$
0
2
}
for
(
key, value
)
in doubled.
sorted
(
by
:
{
$
0
.
key
<
$
1.
key
}
)
{
(
"(key): (value)"
)
}
The output of the above code is:
Runoob: 24
Swift: 22
merging(_:uniquingKeysWith:) merges another dictionary in, and when keys conflict a closure decides which value to keep.
Example
import Foundation
let ages
=
[
"Runoob"
:
10
,
"RUNOOB"
:
5
]
let extra
=
[
"Swift"
:
100
,
"Runoob"
:
99
]
// On key conflict, the closure decides which to keep; here the new value is returned
let merged
=
ages.
merging
(
extra
)
{
current,
new
in
new
}
for
(
key, value
)
in merged.
sorted
(
by
:
{
$
0
.
key
<
$
1.
key
}
)
{
(
"(key) => (value)"
)
}
The output of the above code is:
RUNOOB => 5
Runoob => 99
Swift => 100
The closure's first parameter is the value from the original dictionary, the second is the value from the new dictionary; whichever you return is the one kept.
In the example above, Runoob exists in both dictionaries; the closure returns new, so the result is 99; changing it to current would keep 10.
Use merging when you don't need to modify the original dictionary, and merge(_:uniquingKeysWith:) when you need in-place merging.
Requirements for keys
Keys must conform to the Hashable protocol, because a dictionary relies on hash values to locate elements.
Common types such as strings, integers, floating-point numbers, Booleans, and enums all satisfy this requirement, and custom structs can have the implementation synthesized automatically.
Example
import Foundation
// Make a custom struct conform to Hashable and it can be used as a dictionary key
struct
Site
:
Hashable
{
let name
:
String
}
var visits
:
[
Site
:
Int
]
=
[
:
]
visits
[
Site
(
name
:
"Runoob"
)
]
=
10
visits
[
Site
(
name
:
"RUNOOB"
)
]
=
5
(
visits
[
Site
(
name
:
"Runoob"
)
]
??
0
)
(
visits.
count
)
The output of the above code is:
10
2
Hashable inherits from Equatable, so a type used as a key must also support equality checks.
When all members of a struct are Hashable, the compiler automatically synthesizes the Hashable and Equatable implementations, so you don't need to write them by hand.
Note:Class instances are compared by "reference" by default and don't automatically synthesize a hash from properties. To use a class as a key, you need to implement it yourself Hashable The difference between ==。
Common questions
Below are some of the most common issues in using dictionaries.
Why is dictionary iteration order different every time?
Dictionaries are stored internally with a hash table; element arrangement depends on hash values and capacity, and Swift promises no particular order.
When you need order, sort explicitly, e.g. ages.sorted(by: { $0.key < $1.key }), and don't rely on the observed "insertion order".
Is a dictionary a value type or a reference type?
It's a value type. After assigning to another variable and modifying one, the other is unaffected; like arrays, it's optimized with copy-on-write.
This is completely different from NSDictionary in Objective-C, which shares the same object.
How to write counting scenarios concisely
With the default subscript, counts[word, default: 0] += 1 does "initialize if absent, accumulate if present" in one line.
Using a regular subscript instead requires an if let check first, then assigning back, making the code quite a bit longer.
What type must keys be?
They must conform to Hashable, which the vast majority of standard library types do.
When using a custom struct or enum as a key, just make them conform to Hashable; Swift can synthesize the implementation automatically.