I was just going through the Swift documentation of deinitializers and found that they only exist for classes. So I was just wondering why structs in Swift don't have deinitializers?
-
2Please resd the comments on https://stackoverflow.com/questions/46842577/how-in-swift-to-know-that-struct-is-deleted-from-memory – Sulthan May 17 '18 at 19:52
-
1Supposing that structs did have deinitializers, what would you like to use them for? – Alexander May 17 '18 at 20:07
-
`Deinitializers` are only available on `class` types as described in documentation. – Mannopson May 18 '18 at 02:38
2 Answers
deinit
is for reference types (see https://stackoverflow.com/a/27366050/341994 for what that means) where the object pointed to persists independently until a reference count drops to zero.
A struct is a value type and does not require memory management that would need a deinit
. Structs are not independently persistent the way classes are. Merely setting a property of a struct destroys it and replaces it. Assigning a struct copies it. Structs are created and destroyed in a highly lightweight way. They don’t need to signal their destruction; they are too lightweight for that.

- 515,959
- 87
- 875
- 1,141
Structs are deallocated when they go out of scope. You can't put a deinit
in a struct, but here is a workaround. You can make a struct that has a reference to a class that prints something when deallocated.
class DeallocPrinter {
deinit {
print("deallocated")
}
}
struct SomeStruct {
let printer = DeallocPrinter()
}
So when the struct is deallocated - if you haven't made a copy of the struct, it'll print deallocated when it's deallocated, since the DeallocPrinter will be deallocated at the same time the struct is deallocated.
Also, structs do not really have instances in the sense that classes do (i.e. they don't have an identity), and there also aren't "references" to structs.

- 13,845
- 28
- 135
- 263
-
Your workaround cannot work. It wont print the message until the last copy od the struct goes out of scope. – Sulthan May 17 '18 at 19:48