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.
In this page:
Syntax
var name: Type? = value
var name: Type? = nil // no value
func functionName() -> Type? {
return value or nil
}
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
// Declare a mutable variable `middleName` (a `String?`), initialized to `"Marie"`
var middleName: String? = "Marie"
// Declare a mutable variable `nickname` (a `String?`), initialized to `nil`
var nickname: String? = nil
// Print `middleName as Any` to the console
print(middleName as Any)
// Print `nickname as Any` to the console
print(nickname as Any)
Login to try C/C++/Java/PHP code in the editor
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
// Define the function `findAge` taking `name` and returning a `Int?`
func findAge(for name: String) -> Int? {
// Declare a constant `ages`, set to `["Alice": 30, "Bob": 25]`
let ages = ["Alice": 30, "Bob": 25]
// Return `ages[name]` from this function
return ages[name]
}
// Print `findAge(for: "Alice") as Any` to the console
print(findAge(for: "Alice") as Any)
// Print `findAge(for: "Charlie") as Any` to the console
print(findAge(for: "Charlie") as Any)
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
- Treating an optional value as if it were the underlying value directly, e.g. trying to add an
Int?to anIntwithout unwrapping first. - Force-unwrapping every optional out of habit instead of safely checking for
nilfirst. - Confusing
Int?(an optional Int) withInt(a guaranteed Int); they are different types to the compiler.
Chapter Summary
- An optional is written as
Type?and can hold either a value ornil. - 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: