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

The nil Value

nil is Swift's way of saying "there is nothing here at all," like an empty gift box.

Assigning nil

Only a variable declared with an optional type can be set to nil, representing that it currently holds no value.

Example: Assigning nil

markup
var favoriteColor: String? = "blue"
favoriteColor = nil
print(favoriteColor as Any)

Checking for nil

Comparing an optional to nil with == or != is a straightforward way to check whether it currently holds a value.

Example: Checking for nil

markup
var score: Int? = nil
if score == nil {
    print("No score recorded yet")
} else {
    print("Score is \(score!)")
}
Common Mistakes
  1. Trying to assign nil to a non-optional variable; only optional types can ever hold nil.
  2. Assuming nil in Swift behaves like 0 or an empty string; it specifically represents the total absence of a value.
  3. Forgetting that a freshly declared optional without an initial value implicitly starts as nil.
Chapter Summary
  • nil represents the absence of a value and can only be assigned to optional types.
  • A non-optional variable can never be nil -- the compiler enforces this at compile time.
  • An optional declared without an initial value defaults to nil.
  • Checking if value == nil (or != nil) is a simple way to test for absence.
🔒

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.