0
0
Swiftprogramming~30 mins

Strong reference cycles between classes in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Strong reference cycles between classes
📖 Scenario: Imagine you are building a simple app to manage a library system. You want to keep track of Authors and their Books. Each author can have multiple books, and each book has one author.
🎯 Goal: You will create two classes, Author and Book, that reference each other. Then, you will see how a strong reference cycle can happen and how to fix it using weak references.
📋 What You'll Learn
Create a class called Author with a name property and a books array property.
Create a class called Book with a title property and an author property.
Create an Author instance and a Book instance that reference each other.
Fix the strong reference cycle by making the author property in Book a weak reference.
Print messages when Author and Book instances are deinitialized to observe memory management.
💡 Why This Matters
🌍 Real World
Strong reference cycles can cause memory leaks in apps, making them slower or crash. Understanding how to avoid them is important when building apps that manage related objects.
💼 Career
Swift developers must know how to manage memory and avoid strong reference cycles to write efficient and reliable iOS apps.
Progress0 / 4 steps
1
Create the Author and Book classes
Create a class called Author with a name property of type String and a books property as an empty array of Book. Create a class called Book with a title property of type String and an author property of type Author? (optional).
Swift
Need a hint?

Define two classes with the exact property names and types as described.

2
Create instances and link them
Create an Author instance called author with the name "Jane Austen". Create a Book instance called book with the title "Pride and Prejudice". Set the author property of book to the author instance. Add book to the books array of author.
Swift
Need a hint?

Create the instances with the exact names and values, then link them as described.

3
Add deinitializers to observe memory management
Add deinit methods to both Author and Book classes that print "Author deinitialized" and "Book deinitialized" respectively.
Swift
Need a hint?

Add deinit blocks inside both classes that print the required messages.

4
Fix the strong reference cycle with a weak reference
Change the author property in the Book class to be a weak optional reference by adding the weak keyword before var author: Author?. Then, set both author and book to nil and print "End of program".
Swift
Need a hint?

Make the author property weak and then set both variables to nil to see the deinitializers called.