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.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
Parameters
key
The key the look up in the dictionary.
defaultValue
The default value to use if
key
doesn’t exist in the dictionary.
Return Value
The value associated with key
in the dictionary; otherwise,
defaultValue`.
Discussion
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:
When 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.
Note
Do not use this subscript to modify dictionary values if the dictionary’s Value
type is a class. In that case, the default value and key are not written back to the dictionary after an operation.