Swift·Swift from optionals to SwiftUI

Optionals

Use optional binding, nil coalescing and guard to handle absence.

Beginner 13 min read Lesson 2 of 300 Challenge included
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.

Optionals.swiftSwift
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

Default an optional

Easy

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Collections
Lesson 2 of 300 · 0% of course