Optional Type in Swift

Level 288 keystrokes

Declares an optional String and uses the nil-coalescing operator ?? to print a default when it is nil: prints "Swift", then "Unknown".

Swift code

// String? is an optional String: it holds a String or nil
1var name: String? = "Swift"
// ?? unwraps the value, or uses "Unknown" if it is nil: Swift
2print(name ?? "Unknown")
// Only optionals can be set to nil
3name = nil
// name is nil now, so the default is used: Unknown
4print(name ?? "Unknown")

Output

Swift
Unknown
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.

  • "× 6
  • ?× 5
  • (× 2
  • )× 2
  • =× 2
  • :× 1

More Swift examples at level 2

← Swift typing practice