Swift Deinitializers
A deinitializer is a block that runs just before a class object is removed from memory. Swift writes it as deinit, and it runs automatically with no call from the code.
Setting a variable to nil
The note object is held by an optional variable. Setting that variable to nil runs the deinitializer before the final print.
class Note {
var title: String
init(title: String) {
self.title = title
}
deinit {
print("Note gone: \(title)")
}
}
var note: Note? = Note(title: "List")
print("Made")
note = nil
print("Done")A function scope ends
The session object is local to the runSession function. Its deinitializer line prints after the function body and before the caller moves on.
class Session {
var name: String
init(name: String) {
self.name = name
}
deinit {
print("Session closed")
}
}
func runSession() {
let session = Session(name: "A")
print(session.name)
print("Leaving")
}
print("Start")
runSession()
print("After")Two objects end in order
Each lamp prints its own name as it is removed. The second lamp is set to nil first, so its line prints first.
class Lamp {
var name: String
init(name: String) {
self.name = name
}
deinit {
print("\(name) lamp gone")
}
}
var first: Lamp? = Lamp(name: "Desk")
var second: Lamp? = Lamp(name: "Floor")
second = nil
first = nil
print("End")Example
class Timer {
var label: String
init(label: String) {
self.label = label
}
deinit {
print("Timer \(label) stopped")
}
}
func makeTimer() -> String {
let timer = Timer(label: "Tea")
return timer.label
}
let name = makeTimer()
print(name)
print("Next line")Key points
- Only classes can have a deinitializer.
- A deinitializer takes no parameters and returns nothing.
- Swift runs the deinitializer when the last reference to the object goes away.
- Setting an optional variable to nil removes its reference at that line.
- A local object is removed when the function that made it ends.
- Prints inside deinit make the exact moment visible.
In this example, the makeTimer function creates a Timer and returns its label as text. The timer itself is removed when the function ends, so its stopped line prints first. The caller then prints the returned label, which the removal did not affect.
Note
A program cannot call deinit directly, and each class can have at most one.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A local object is created inside a function, and nothing outside the function holds it. When does its deinitializer run?