Challenge - 5 Problems
Deinitializer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code using a deinitializer?
Consider this Swift class with a deinitializer. What will be printed when the instance is created and then set to nil?
Swift
class Printer { let message: String init(message: String) { self.message = message print("Init: \(message)") } deinit { print("Deinit: \(message)") } } var p: Printer? = Printer(message: "Hello") p = nil
Attempts:
2 left
💡 Hint
Think about when the deinitializer runs in Swift.
✗ Incorrect
The initializer prints when the object is created. The deinitializer runs when the object is destroyed, which happens when the variable is set to nil.
❓ Predict Output
intermediate2:00remaining
What happens if a class instance with a deinitializer is never set to nil?
Given this Swift code, what will be the output?
Swift
class Logger { deinit { print("Logger is being deinitialized") } } func createLogger() { let log = Logger() print("Logger created") } createLogger()
Attempts:
2 left
💡 Hint
Think about the lifetime of local variables in functions.
✗ Incorrect
The Logger instance is created inside the function and destroyed when the function ends, triggering the deinitializer.
🔧 Debug
advanced2:30remaining
Why does this deinitializer not print anything?
Examine this Swift code. Why does the deinitializer message never appear?
Swift
class Resource { deinit { print("Resource cleaned up") } } var r1: Resource? = Resource() var r2 = r1 r1 = nil // r2 is still holding the instance
Attempts:
2 left
💡 Hint
Think about how Swift manages memory with references.
✗ Incorrect
The instance is kept alive by r2, so deinit does not run until all references are gone.
❓ Predict Output
advanced2:30remaining
What is the output of this Swift code with multiple instances and deinitializers?
Analyze this Swift code and select the correct output sequence.
Swift
class Item { let id: Int init(id: Int) { self.id = id print("Init \(id)") } deinit { print("Deinit \(id)") } } var items: [Item]? = [Item(id: 1), Item(id: 2)] items?.append(Item(id: 3)) items = nil
Attempts:
2 left
💡 Hint
Think about the order of initialization and deinitialization of array elements.
✗ Incorrect
All three items are initialized in order. When the array is set to nil, all items are deinitialized in reverse order (last to first).
🧠 Conceptual
expert2:00remaining
Which statement about Swift deinitializers is true?
Choose the correct statement about deinitializers in Swift classes.
Attempts:
2 left
💡 Hint
Recall how Swift manages memory and object lifecycle.
✗ Incorrect
Deinitializers run once automatically when the last strong reference to a class instance is removed. They cannot be called manually. Structs and enums do not have deinitializers.