Optionals
Use optional binding, nil coalescing and guard to handle absence.
What you will be able to do
- Declare optional types with ?.
- Use if let or guard let to unwrap.
- Use ?? for defaults.
- Avoid ! in production code.
In plain English
An optional either has a value or is nil. if let and guard let unwrap safely; ?? supplies a default. Avoid force unwrapping with ! unless the value is guaranteed by the API.
func greet(_ name: String?) -> String {
guard let name, !name.isEmpty else { return "Hello, friend" }
return "Hello, \(name)"
}
print(greet(nil))
print(greet("Ada"))Your turn
EasyDefault an optional
Use ?? to default a nullable name to "friend".
SWIFT · starter
let safe =Check your understanding before moving on.
Knowledge checkQuestion 1
Which operator provides a default for nil?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.