0Pricing
Swift Academy · Lesson

Nil Coalescing and Ternary with Optionals

Using ?? for default values and chaining nil-coalescing operators.

Nil Coalescing and Ternary with Optionals is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

The nil coalescing operator `??` provides a default value when an optional is nil. Combined with the ternary operator, it gives you concise, expressive optional handling.

The ?? Operator

```swift let name: String? = nil let display = name ?? "Guest" print(display) // "Guest" let known: String? = "Alice" print(known ?? "Guest") // "Alice" ``` If the optional is non-nil, its unwrapped value is used. Otherwise the default is used.

Short-Circuit Evaluation

The right-hand side of `??` is only evaluated when the left side is nil: ```swift func expensiveDefault() -> String { print("Computing...") return "Default" } let val: String? = "Existing" let result = val ?? expensiveDefault() // expensiveDefault not called ```

Chaining ??

Chain multiple `??` operators to try several fallbacks: ```swift let primary: String? = nil let secondary: String? = nil let fallback = "Anonymous" let user = primary ?? secondary ?? fallback print(user) // "Anonymous" ``` Evaluation stops at the first non-nil value.

?? with Computed Properties

```swift struct Config { var theme: String? var displayTheme: String { theme ?? "light" } } var c = Config() print(c.displayTheme) // "light" c.theme = "dark" print(c.displayTheme) // "dark" ``` Clean default-value pattern in computed properties.

Ternary Operator with Optionals

The ternary `condition ? a : b` can work with optional checks: ```swift let score: Int? = 85 let label = score != nil ? "\(score!)" : "No score" ``` But `??` is usually cleaner: ```swift let label = score.map { "\($0)" } ?? "No score" ```

Optional.map for Transforming

Transform an optional's wrapped value without unwrapping: ```swift let maybeInt: Int? = 42 let maybeStr = maybeInt.map { "Value: \($0)" } // Optional("Value: 42") let nilInt: Int? = nil let nilStr = nilInt.map { "Value: \($0)" } // nil ```

flatMap for Optional Chaining

Use `flatMap` when the transform itself returns an optional: ```swift let str: String? = "123" let num = str.flatMap { Int($0) } // Optional(123) let bad: String? = "abc" let nil2 = bad.flatMap { Int($0) } // nil ```

??= Assignment Operator (Not Built-in)

Swift doesn't have `??=` built-in, but you can simulate it: ```swift var cache: [String: Int] = [:] // Assign only if nil: if cache["key"] == nil { cache["key"] = expensiveCompute() } // Or with a helper: func ??= (lhs: inout T?, rhs: @autoclosure () -> T) { if lhs == nil { lhs = rhs() } } ```

Readability Guidelines

Choose the right tool: • `??` — simple default values • `if let` — when you need the unwrapped value in multiple statements • `guard let` — precondition + early exit • `.map` / `.flatMap` — transforming without unwrapping Avoid `!` forced unwrap unless the nil case truly cannot happen.

Quick Check

What does `optional ?? default` return when `optional` is `nil`?

Recap

Key takeaways: • `a ?? b` — returns `a`'s value if non-nil, else `b` • Short-circuits: `b` is only evaluated when `a` is nil • Chain: `a ?? b ?? c` • `.map` transforms the wrapped value; `.flatMap` handles transform-returns-Optional • Prefer `??` over ternary + forced unwrap Next: optional chaining with `?.`

Frequently asked questions

Is the “Nil Coalescing and Ternary with Optionals” lesson free?

Yes — the full text of “Nil Coalescing and Ternary with Optionals” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Nil Coalescing and Ternary with Optionals”?

Using ?? for default values and chaining nil-coalescing operators. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Nil Coalescing and Ternary with Optionals” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. if let and guard let Binding
  2. Nil Coalescing and Ternary with Optionals
  3. Optional Chaining ?. Operator
  4. Implicitly Unwrapped Optionals and When to Avoid Them
← Back to Swift Academy