Dictionary Default Subscripts
Read dictionary values with built-in defaults.
Dictionary Lookups Are Optional
Looking up a key with dict[key] returns an optional, because the key might not exist. That optional needs handling.
let ages = ["Ann": 30]
let bob = ages["Bob"]
print(bob as Any)The Default Subscript
Swift offers a subscript with a default: dict[key, default: value]. If the key is missing, you get the default instead of nil.
let ages = ["Ann": 30]
print(ages["Bob", default: 0])
print(ages["Ann", default: 0])All lessons in this course
- The Nil-Coalescing Operator
- Chaining Default Values
- Defaults in Function Parameters
- Dictionary Default Subscripts