← Back to Swift Course | Chapter 5: Optionals | Lesson 1 of 8

Optional Basics

An optional is a box that might have something inside it, or might be completely empty -- and Swift makes you check before you look.

Declaring an Optional

Adding a ? after a type marks it as optional, meaning the variable can hold either a value of that type or nil.

Example: Declaring an Optional

markup
var middleName: String? = "Marie"
var nickname: String? = nil
print(middleName as Any)
print(nickname as Any)

Why Optionals Exist

Optionals make the possibility of a missing value explicit in the type system, forcing you to handle the nil case deliberately instead of crashing at runtime unexpectedly.

Example: Why Optionals Exist

markup
func findAge(for name: String) -> Int? {
    let ages = ["Alice": 30, "Bob": 25]
    return ages[name]
}
print(findAge(for: "Alice") as Any)
print(findAge(for: "Charlie") as Any)
Common Mistakes
  1. Treating an optional value as if it were the underlying value directly, e.g. trying to add an Int? to an Int without unwrapping first.
  2. Force-unwrapping every optional out of habit instead of safely checking for nil first.
  3. Confusing Int? (an optional Int) with Int (a guaranteed Int); they are different types to the compiler.
Chapter Summary
  • An optional is written as Type? and can hold either a value or nil.
  • Optionals are Swift's explicit way of representing the absence of a value.
  • You cannot use an optional's value directly without first unwrapping it.
  • Optionals prevent an entire class of null-reference crashes common in other languages.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.