0Pricing
Swift Academy · Lesson

Optionals intro: ?, nil, if let, guard let, ??

Introduce optionals: declaring with ?, representing missing values with nil, and unwrapping via if let, guard let, and ??

What is an Optional?

Optionals represent a value that may be present or nil. Add ? to a type to make it optional.

  • Handle absence explicitly
  • Avoids many crashes

if let binding

Declare with ?, then use if let to unwrap safely when present.

var nickname: String? = nil
print("nickname =", String(describing: nickname))

// Optional binding with if let
let input: String? = "Ada"
if let name = input {
    print("Hello, \\(name)")
} else {
    print("No name")
}

All lessons in this course

  1. let vs var, type inference, literals, tuples
  2. Core types: numbers, Bool, String, Character
  3. Optionals intro: ?, nil, if let, guard let, ??
← Back to Swift Academy