0
0
Swiftprogramming~30 mins

Optional chaining with ?. in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional chaining with ? in Swift
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(authorName ?? "Author not found") to print the name or fallback.