Optionals and why Swift has them

Swift language Junior Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

What does this print?

let input = "42a"
let n = Int(input) ?? -1
print(n)
let name: String? = nil
print(name?.count ?? 0)
Options
Hint 1 of 1

Does Int("42a") succeed?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B -1 then 0

Correct. The failed parse falls back to -1, and the nil chain falls back to 0.

Why not the others?
  • A 42 then 0. Int("42a") fails and returns nil, because the whole string must be a number.
  • C -1 then nil. ?? 0 replaces the nil from optional chaining.
  • D It crashes. Nothing is force-unwrapped.

30-second answer

An optional is either a value or nil, written T?, and the compiler makes you handle the nil case before using it. That moves 'null pointer' crashes to compile time. Unwrap safely with if let, guard let, ?? or optional chaining; force unwrapping with ! is a deliberate crash if nil.

Practise saying it · 30 s. No recording, just a timer

Explain optionals and safe unwrapping.

Say your answer out loud, then check which of these points you covered:

  • Value or nil
  • Compiler forces handling
  • if let / guard let / ?? / ?.

Deep dive

Optional is an enum with cases .some(Wrapped) and .none.

guard let x else { return } keeps the happy path unindented.

Optional chaining (user?.address?.city) short-circuits to nil.

Implicitly unwrapped optionals (T!) are mostly for IBOutlets and two-phase init.

Common mistakes

  • Force unwrapping values that come from the network or the user.
  • Nesting many if lets instead of using guard.

Senior take & follow-ups

Seniors treat ! as an assertion with a reason, not a shortcut.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does map on an optional do?

    Show hint

    Transforms the value if present, otherwise stays nil.

  2. When is ! acceptable?

    Show hint

    When nil would be a programmer error you want to catch immediately.

Suggest a fix if something here is wrong or out of date.