🐦 Swift

Optionals

Lesson 2 of 5 ~5 min

Optionals are one of Swift's most powerful features. They let you represent a value that might or might not exist. Instead of crashing when a value is missing, Swift forces you to handle the absence explicitly.

You'll see optionals everywhere in Swift code — in API responses, user input, and optional configuration values.

What is an Optional?

An optional type is written with a ? after the type. It means the variable holds either a value or nil (nothing).

Editor
Swift
Output

Try it

Set nickname to nil and see how the if let block and nil coalescing operator handle the missing value.

Unwrapping Optionals

Swift gives you several safe ways to unwrap an optional:

// 1. if let — safe unwrapping
if let value = optionalVar {
  print(value) // only runs if not nil
}

// 2. guard let — early exit
func greet(_ name: String?) {
  guard let name = name else {
    print("No name provided")
    return
  }
  print("Hello, \(name)!")
}

// 3. ?? — nil coalescing (provide default)
let result = optionalVar ?? "default"

// 4. Optional chaining (?.)
let count = name?.count  // nil if name is nil

Quiz

What operator provides a default value for an optional?
Challenge

Create an optional String, unwrap it with if let, and provide a default value using ?? (nil coalescing).