← 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.
Syntax
swift
var name: Type? = value
name = nil

if name == nil {
    // no value
}

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
// Declare a mutable variable `favoriteColor` (a `String?`), initialized to `"blue"`
var favoriteColor: String? = "blue"
favoriteColor = nil
// Print `favoriteColor as Any` to the console
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
// Declare a mutable variable `score` (a `Int?`), initialized to `nil`
var score: Int? = nil
// Check whether `score == nil`
if score == nil {
    // Print "No score recorded yet" to the console
    print("No score recorded yet")
// Otherwise, run this branch
} else {
    // Print "Score is \(score!)" to the console
    print("Score is \(score!)")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.