Junior — Middle
In what context or under what circumstances is the deinit method called in Swift?
sobes.tech AI
Answer from AI
The deinit method in Swift is called automatically just before an instance of a class is deallocated from memory. It is a destructor that allows you to release resources, close files, cancel observers, and perform other cleanup.
deinit is called in the following circumstances:
- When the reference count to the object reaches zero (ARC — Automatic Reference Counting).
- Before the object is deinitialized and memory is freed.
Example of using deinit:
class FileHandler {
let fileName: String
init(fileName: String) {
self.fileName = fileName
print("File opened: \(fileName)")
}
deinit {
print("File closed: \(fileName)")
}
}
func example() {
let handler = FileHandler(fileName: "data.txt")
// handler is used inside the function
} // here, handler goes out of scope, deinit is called
Thus, deinit is useful for managing resources and cleanup when an object is destroyed.