Dictionary Access in Swift

Level 271 keystrokes

Reads dictionary values by key; a key lookup returns an optional, so ?? supplies 0 for the missing key "c". Prints 1, then 0.

Swift code

// A dictionary literal of type [String: Int]
1let dict = ["a": 1, "b": 2]
// dict["a"] is Int? (Optional(1)); ?? unwraps it: 1
2print(dict["a"] ?? 0)
// "c" is not a key, so the lookup is nil and the default is used: 0
3print(dict["c"] ?? 0)

Output

1
0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 8
  • ?× 4
  • [× 3
  • ]× 3
  • :× 2
  • (× 2
  • )× 2
  • ,× 1
  • =× 1

More Swift examples at level 2

← Swift typing practice