The nil Value
nil is Swift's way of saying "there is nothing here at all," like an empty gift box.
In this page:
Syntax
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
// 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)
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
// 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!)")
}
Login to try C/C++/Java/PHP code in the editor
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
- 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: