To get the value for a specific key from a dictionary, the access syntax can be used: The dictionary is followed by an opening square bracket [, the key, and ends with a closing square bracket ].
Accessing a key returns an optional: If the key is found in the dictionary, the value for the given key is returned, and if the key is not found, nil is returned.
// Declare a constant that has type `{Bool: Int}`,
// a dictionary mapping integers to booleans.
//
let booleans = {
1: true,
0: false
}
// The result of accessing a key has type `Bool?`.
//
booleans[1] // is `true`
booleans[0] // is `false`
booleans[2] // is `nil`
// Invalid: Accessing a key which does not have type `Int`.
//
booleans["1"]
// Declare a constant that has type `{Bool: Int}`,
// a dictionary mapping booleans to integers.
//
let integers = {
true: 1,
false: 0
}
// The result of accessing a key has type `Int?`
//
integers[true] // is `1`
integers[false] // is `0`
To set the value for a key of a dictionary, the access syntax can be used as well.
// Declare a constant that has type `{Int: Bool}`,
// a dictionary mapping booleans to integers.
//
let booleans = {
1: true,
0: false
}
// Assign new values for the keys `1` and `0`.
//
booleans[1] = false
booleans[0] = true
// `booleans` is `{1: false, 0: true}`