The nil Value
nil is Swift's way of saying "there is nothing here at all," like an empty gift box.
In this page:
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
var favoriteColor: String? = "blue"
favoriteColor = nil
print(favoriteColor as Any)
Login to try C/C++/Java/PHP code in the editor
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
var score: Int? = nil
if score == nil {
print("No score recorded yet")
} else {
print("Score is \(score!)")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Trying to assign
nilto a non-optional variable; only optional types can ever holdnil. - Assuming
nilin Swift behaves like0or an empty string; it specifically represents the total absence of a value. - Forgetting that a freshly declared optional without an initial value implicitly starts as
nil.
Chapter Summary
nilrepresents 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: