0
0
Swiftprogramming~30 mins

Deinitializers for cleanup in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Deinitializers for cleanup
📖 Scenario: Imagine you are managing a simple library system where books are borrowed and returned. When a book is no longer needed, it should clean up by announcing it is removed from the system.
🎯 Goal: You will create a Book class with a deinitializer that prints a message when a book object is removed from memory.
📋 What You'll Learn
Create a Book class with a title property
Add an initializer to set the title
Add a deinitializer that prints a message including the title
Create and remove book instances to see the deinitializer in action
💡 Why This Matters
🌍 Real World
Deinitializers are used in apps to release resources like files, network connections, or memory when objects are no longer needed.
💼 Career
Understanding deinitializers is important for Swift developers to write efficient, memory-safe apps and avoid resource leaks.
Progress0 / 4 steps
1
Create the Book class with a title property
Create a class called Book with a property title of type String. Add an initializer that takes a title parameter and sets the property.
Swift
Need a hint?

Use class Book to define the class. Use let title: String for the property. Write an init method to set title.

2
Add a deinitializer to announce when a book is removed
Add a deinitializer deinit inside the Book class that prints "Removing book titled: \(title)".
Swift
Need a hint?

Use deinit { } to define the deinitializer. Inside it, use print with the message including title.

3
Create a book instance and then remove it
Create a variable myBook and assign it a new Book instance with the title "Swift Programming". Then set myBook to nil to remove the instance.
Swift
Need a hint?

Create myBook as an optional Book and assign it a new instance. Then set myBook = nil to trigger the deinitializer.

4
Run the program to see the deinitializer output
Run the program and observe the output. It should print Removing book titled: Swift Programming when myBook is set to nil.
Swift
Need a hint?

When you run the program, the message from the deinitializer should appear in the output.