📖 Scenario: Imagine you are building a simple app to manage a library. Each Library has a Book, and each Book has an Author. Sometimes, the library might not have a book, or the book might not have an author yet.
🎯 Goal: You will create classes for Library, Book, and Author. Then, you will use optional chaining with ? to safely access the author's name through the library.
📋 What You'll Learn
Create a class Author with a property name of type String.
Create a class Book with an optional property author of type Author?.
Create a class Library with an optional property book of type Book?.
Use optional chaining with ? to access the author's name from the library.
Print the author's name if it exists, or print "Author not found" if it does not.
💡 Why This Matters
🌍 Real World
Optional chaining is very useful when working with data that might be missing or incomplete, such as user profiles, network responses, or database records.
💼 Career
Understanding optional chaining helps you write safer Swift code that avoids crashes due to nil values, a key skill for iOS app development.
Progress0 / 4 steps
1
Create classes for Author, Book, and Library
Create a class called Author with a property name of type String. Then create a class called Book with an optional property author of type Author?. Finally, create a class called Library with an optional property book of type Book?.
Swift
Hint
Remember to use ? for optional properties author and book.
2
Create instances for Author, Book, and Library
Create an instance of Author called author with the name "Jane Austen". Then create an instance of Book called book with the author instance. Finally, create an instance of Library called library with the book instance.
Swift
Hint
Create the instances exactly as described with the given names and values.
3
Use optional chaining to access the author's name
Use optional chaining with library.book?.author?.name to create a constant called authorName that safely accesses the author's name from the library.
Swift
Hint
Use ? after book and author to safely access name.
4
Print the author's name or a fallback message
Write a print statement that prints authorName if it is not nil, or prints "Author not found" if authorName is nil. Use the nil-coalescing operator ?? for this.
Swift
Hint
Use print(authorName ?? "Author not found") to print the name or fallback.
Practice
(1/5)
1. What does the ?. operator do in Swift when used with optionals?
easy
A. It forces unwraps the optional and crashes if nil.
B. It converts the optional to a non-optional value automatically.
C. It safely accesses a property or method and returns nil if the optional is nil.
D. It assigns a default value if the optional is nil.
Solution
Step 1: Understand optional chaining purpose
The ?. operator is used to safely access properties or methods on an optional value.
Step 2: Behavior when optional is nil
If the optional is nil, the chaining stops and returns nil instead of crashing.
Final Answer:
It safely accesses a property or method and returns nil if the optional is nil. -> Option C
Quick Check:
Optional chaining = safe access with nil return [OK]
Hint: Remember: ? stops if nil, no crash happens [OK]
Common Mistakes:
Confusing optional chaining with forced unwrapping
Thinking it unwraps optionals automatically
Assuming it provides default values
2. Which of the following is the correct syntax to safely access the name property of an optional person object using optional chaining?
easy
A. person->name
B. person!.name
C. person.name?
D. person?.name
Solution
Step 1: Identify correct optional chaining syntax
Optional chaining uses ?. between the optional variable and the property.
Step 2: Check each option
person?.name uses person?.name, which is correct syntax. person!.name forces unwraps with !. person.name? places ? incorrectly. person->name uses invalid operator.
Hint: Use ?. right before the property to chain safely [OK]
Common Mistakes:
Using ! instead of ? for optional chaining
Placing ? after the property name
Using invalid operators like ->
3. Consider the following Swift code:
class Person {
var pet: Pet?
}
class Pet {
var name: String
init(name: String) { self.name = name }
}
let person = Person()
let petName = person.pet?.name
print(petName)
What will be printed?
medium
A. Optional(nil)
B. nil
C. An empty string
D. Runtime error
Solution
Step 1: Analyze the optional chaining result
Since person.pet is nil (not assigned), person.pet?.name returns nil of type String?.
Step 2: Understand print output of optional nil
Printing an optional value that is nil in Swift shows Optional(nil) because the variable itself is an optional.
Final Answer:
Optional(nil) -> Option A
Quick Check:
print(String? nil) = Optional(nil) [OK]
Hint: Printing optional nil shows 'Optional(nil)', not 'nil' [OK]
Common Mistakes:
Thinking print shows nil
Expecting empty string output
Thinking it causes runtime error
4. The following Swift code causes a compile error. What is the mistake?
struct Car {
var owner: Person?
}
let car = Car()
let ownerName = car.owner?.name!
medium
A. Using forced unwrap (!) after optional chaining without parentheses
B. Missing initialization of car variable
C. Incorrect use of optional chaining operator
D. Person type does not have a name property
Solution
Step 1: Identify forced unwrap misuse
The code uses car.owner?.name! which tries to force unwrap the property without parentheses.
Step 2: Correct syntax for forced unwrap after optional chaining
Forced unwrap must be applied to the entire optional chaining expression with parentheses like (car.owner?.name)!.
Final Answer:
Using forced unwrap (!) after optional chaining without parentheses -> Option A
Quick Check:
Force unwrap after optional chaining needs parentheses [OK]
Hint: Wrap optional chain in () before ! to force unwrap [OK]
Common Mistakes:
Forgetting parentheses around optional chain before !
Assuming optional chaining can be forced unwrapped directly
Ignoring compiler error details
5. Given the following classes:
class Address {
var city: String?
}
class User {
var address: Address?
}
let user = User()
Which code safely prints the city name if it exists, or "Unknown" if city or address is nil?
hard
A. print(user.address.city ?? "Unknown")
B. print(user.address?.city ?? "Unknown")
C. print(user.address!.city!)
D. print(user.address?.city!)
Solution
Step 1: Understand optional chaining with nil coalescing
Using user.address?.city safely accesses city, returning nil if address or city is nil.
Step 2: Use nil coalescing operator to provide default
The ?? "Unknown" provides "Unknown" if the optional is nil, avoiding crashes.
Final Answer:
print(user.address?.city ?? "Unknown") -> Option B
Quick Check:
Optional chaining + ?? = safe access with default [OK]
Hint: Combine ?. with ?? to provide default value safely [OK]
Common Mistakes:
Forcing unwraps causing runtime crashes
Not handling nil for nested optionals
Using optional chaining without default fallback
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.