Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift Basics  ›  Lesson

Optionals

Swift Basics 12 minAn optional type may hold a value or nil, and must be safely unwrapped with if let, guard let or ?? before its value is used.

Optionals

A TrailLog hike may or may not have a note, a photo, or a finish time. In many languages "no value" hides as null inside any variable, waiting to crash. Swift puts the possibility of absence into the type itself, so you cannot forget it.

The rule

A ? type is a box that may be empty — open it before use.

String? means "a String, or nothing". Nothing is written nil. A plain String can never be nil.

var note: String? = nil
note = "Muddy after the rain"

You cannot use note as a String directly; you must unwrap it first. Four tools, from safest to riskiest:

// 1. if let — run a block only when there is a value
if let note {
    print("Note: \(note)")
}

// 2. guard let — leave early when there is no value
func showPhoto(_ photo: UIImage?) {
    guard let photo else { return }
    imageView.image = photo      // photo is unwrapped from here on
}

// 3. ?? — supply a default
let shown = note ?? "No note"

// 4. ! — force unwrap: crashes if nil
let risky = note!

There is also optional chaining with ?.: hike.photo?.size returns an optional size, or nil if there is no photo, without crashing.

Many everyday APIs return optionals because they can fail: Int("12") gives 12, but Int("twelve") gives nil, so its type is Int?. Dictionary lookups return optionals too, because the key may be missing.

The shortcut

When you meet an optional, pick the tool by asking "What should happen when it is empty?"

  • Skip some work → if let
  • Stop the whole function → guard let
  • Use a fallback value → ??
  • It truly cannot be empty and a crash is the right signal → ! (rare)
Showing a hike's finish timeStep 1 of 4
  1. The value

    hike.finishedAt is Date? because an ongoing hike has not finished.

The trap is reaching for ! to silence the compiler. Every ! is a promise that the value is never nil; when that promise breaks, the app crashes in front of the user.

Drills

Answer fast — trust the rule.

quick drill

What is the type of Int("twelve")?

quick drill

note is nil. What is note ?? "No note"?

quick drill

A function cannot do anything useful without a user ID that might be missing. Which tool fits best?

quick drill

hike.photo is nil. What does hike.photo?.size produce?

quick drill

Which line crashes when note is nil?

Remember

  • A ? type may be empty (nil); unwrap it before use.
  • Choose by the empty case: skip → if let, stop → guard let, default → ??.
  • Trap: ! is a crash waiting for the one time the value is missing.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainUnwrap three ways

A hike has photo: UIImage?, note: String? and trailID: String?. The photo is shown only if present, the note falls back to "No note", and saving is impossible without a trail ID. Say which unwrapping tool fits each and why, and explain when ! would be acceptable.