In Swift, which types can declare a deinit, what is a deinitializer allowed to do, and how does it run in a class hierarchy?
answer
- reference types, plus one exception
- no parameters, no parentheses
- never called directly
- subclass first, then superclass
basics
~20 sClasses and actors can declare one deinit, and since Swift 5.9 so can noncopyable structs, though not yet noncopyable enums. It takes no parameters, cannot be called directly, can read the instance's properties, and a subclass's deinit runs before its superclass's, which runs automatically.
solid answer
~50 sA `deinit` is cleanup code that runs just before an instance is destroyed. Classes and actors can declare one; since Swift 5.9 a noncopyable (`~Copyable`) struct can too (a noncopyable enum still cannot), while an ordinary copyable struct or enum gets `deinitializer cannot be declared in struct 'Handle' that conforms to 'Copyable'`. A class has at most one, written `deinit { ... }` with no parentheses or parameters, and it must be in the type's body, not an extension. You never call it yourself (`deinitializers cannot be accessed`). Inside, the instance is still intact, so it can read every property, which is how it closes a file descriptor or removes an observer. In a hierarchy, the subclass's `deinit` runs first and the superclass's runs automatically at its end, even when the subclass declares none. When it runs is decided by ARC.
code
swift · 23 linesclass Shape {
let name: String
init(name: String) { self.name = name }
deinit { print("Shape deinit: \(name)") }
}
class Circle: Shape {
deinit { print("Circle deinit: \(name)") }
}
struct FileDescriptor: ~Copyable {
let fd: Int32
deinit { print("close fd \(fd)") }
}
do {
let c = Circle(name: "ring")
print("using \(c.name)")
}
do {
let file = FileDescriptor(fd: 3)
print("reading fd \(file.fd)")
}go deeper
Recall the syntax with no parentheses, that classes are the usual home of deinit, and that you never call it yourself.
Explain the hierarchy order, why the instance's properties are still usable inside deinit, and why copyable structs and enums (and, for now, noncopyable enums) cannot declare one.
Show where deinit is the right cleanup hook, such as a noncopyable wrapper around a file descriptor, and why it must stay short and synchronous.
Decide where resource cleanup lives in a codebase: explicit close methods, deinit on reference types, or noncopyable owners whose deinit makes the cleanup unavoidable.
## What a deinitializer is A **deinitializer** is code that runs immediately before an instance is destroyed. It exists for **cleanup** that the language cannot do for you: closing a file descriptor, releasing a C resource, removing an observer, logging. You write it with the `deinit` keyword and a body, and nothing else: ```swift deinit { // release resources } ``` ## Which types can declare one | Type | `deinit` allowed? | |---|---| | `class` | Yes, at most one per class | | `actor` | Yes | | noncopyable `struct` (`~Copyable`, Swift 5.9) | Yes | | noncopyable `enum` | Not yet: `deinitializers are not yet supported on noncopyable enums` | | ordinary (copyable) `struct` / `enum` | No: `deinitializer cannot be declared in struct 'Handle' that conforms to 'Copyable'` | | an `extension` of any type | No: `deinitializers may only be declared within a class, actor, or noncopyable type` | A copyable value can be copied by any assignment, so there is no single value whose end would be the moment to clean up. A noncopyable value has exactly one owner at a time, so its end is a well-defined event, and SE-0390 (Swift 5.9) allowed `deinit` there, for structs; Swift 6.4 still rejects it on a noncopyable enum. The Swift book's deinitialization chapter still says deinitializers are only available on class types; the compiler accepts the broader set above. ## The rules of the declaration - **No parameters and no parentheses**: `deinit { }`, never `deinit() { }`. - **No effects in the signature**: it cannot be marked `throws` or `async`, and calling an `async` function inside it fails with `'async' call in a function that does not support concurrency`. - **Never called directly**: `self.deinit()` or `super.deinit()` fails with `deinitializers cannot be accessed`. - **One per class**, declared in the type's own body. ## What it can do Because the instance is not deallocated until **after** its deinitializer finishes, the body can: 1. read and use **all stored properties**, including inherited ones; 2. call the instance's own methods; 3. release whatever the instance owns outside Swift's memory management, such as a file descriptor, a socket or a manually allocated buffer. Keep it short and synchronous. Heavy work, or anything that assumes a particular thread, does not belong there, and the exact moment it runs is not something to build logic on. ## Order in a class hierarchy Superclass deinitializers are **inherited** and **always run**: - the most derived class's `deinit` runs **first**; - the superclass's `deinit` is called **automatically** at the end of it, and so on up to the root; - a subclass with no `deinit` of its own still triggers its superclass's. In the example, destroying a `Circle` prints `Circle deinit: ring` and then `Shape deinit: ring`. There is no `super.deinit()` to write, and trying to write one is an error. ## Noncopyable types For a `~Copyable` struct such as `FileDescriptor`, the `deinit` runs when the single owner's value is destroyed, which makes it a natural place to close the descriptor. Ending such a value **without** running the deinitializer (`discard self` in a consuming method) and the rest of the ownership model are covered in the lesson on noncopyable types. ## Typical uses and pitfalls - **Good uses**: closing a descriptor or socket the instance opened, freeing memory allocated with an unsafe pointer, unregistering a callback the instance installed, or a log line while chasing a leak. - **Pitfall**: treating `deinit` as a place for work that must happen at a specific time, such as saving user data; the save belongs in an explicit method the owner calls. - **Pitfall**: doing slow or blocking work there, since it runs inline wherever the last owner releases the instance. ## What this question is not about When a class instance's deinitializer actually runs depends on automatic reference counting (strong references, cycles, when the last reference ends), which is the material on ARC and object lifetime. Actor deinitializers that need the actor's isolation are covered with actors.
- Do you call super.deinit() at the end of a subclass deinitializer?No. The superclass deinitializer runs automatically at the end of the subclass's, and runs even if the subclass declares none. Writing `super.deinit()` is a compile error: `deinitializers cannot be accessed`.
- Why can a noncopyable struct declare deinit when a normal struct cannot?A copyable struct can be copied freely, so there is no single value whose end would trigger cleanup. A `~Copyable` struct has exactly one owner at a time, so its destruction is a well-defined event; Swift 5.9 (SE-0390) allows a `deinit` there, which suits wrappers around file descriptors or other unique resources.
- Any Swift struct can declare a deinit to clean up its resources.
- A subclass deinitializer must end with a super.deinit() call.
- You can call deinit() yourself to release an object early.
- deinit can be declared in an extension like any other member.
- A deinitializer can await an async cleanup call.