0Pricing
Swift Academy · Lesson

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

  1. The Nil-Coalescing Operator
  2. Chaining Default Values
  3. Defaults in Function Parameters
  4. Dictionary Default Subscripts
← Back to Swift Academy