Dictionary Types
Dictionaries have the form {K: V}
, where K
is the type of the key, and V
is the type of the value. For example, a dictionary with Int
keys and Bool
values has type {Int: Bool}
.
// Declare a constant that has type `{Int: Bool}`,
// a dictionary mapping integers to booleans.
//
let booleans = {
1: true,
0: false
}
// Declare a constant that has type `{Bool: Int}`,
// a dictionary mapping booleans to integers.
//
let integers = {
true: 1,
false: 0
}
Dictionary types are covariant in their key and value types. For example, [Int: String]
is a subtype of [AnyStruct: String]
and also a subtype of [Int: AnyStruct]
. This is safe because dictionaries are value types and not reference types.
Last updated
Was this helpful?