25

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

29

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
23

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.

Nitish
  • 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