Accesses the value with the given key. If the dictionary doesn’t contain the given key, accesses the provided default value as if the key and default value existed in the dictionary.
- Xcode 9.0+
- Swift Standard Library
The key the look up in the dictionary.
The default value to use if
keydoesn’t exist in the dictionary.
The value associated with
key in the dictionary
; otherwise, defaultValue`.
Use this subscript when you want either the value for a particular key or, when that key is not present in the dictionary, a default value. This example uses the subscript with a message to use in case an HTTP response code isn’t recognized:
When a dictionary’s
Value type has value semantics, you can use this subscript to perform in-place operations on values in the dictionary. The following example uses this subscript while counting the occurences of each letter in a string:
letter is executed with a value of
letter that isn’t already a key in
letter, the specified default value (
0) is returned from the subscript, incremented, and then added to the dictionary under that key.