Deinitializers and Memory Lifecycle
Using deinit to clean up resources before an object is deallocated.
Welcome
Swift classes can define a `deinit` that runs just before the instance is deallocated. Understanding the full object lifecycle — init → use → deinit — is key to resource management.
What is deinit?
```swift
class FileHandle {
let path: String
init(path: String) { self.path = path; print("Opened \(path)") }
deinit { print("Closed \(path)") }
}
do {
let f = FileHandle(path: "/tmp/log.txt")
} // deinit called here when f goes out of scope
```
All lessons in this course
- Class Inheritance and the super Keyword
- override, final and Preventing Subclassing
- Type Casting: is, as?, as! and as
- Deinitializers and Memory Lifecycle