In swift class type has method deinit()
in which we can define that instance of class will be removed from memory. How we can know for struct that it will be removed from memory?
For example,
struct Vehicle { ... }
var v: Vehicle? = Vehicle()
v = nil
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.
During an interview I was asked to outline the differences between structs and classes in Swift. Among my points, I made the argument that structs are stored in the stack (space for them is reserved at compile-time) whereas classes are stored in the heap (space is allocated at run-time).
Structs are thread-safe Since structs are unique copies, it's only possible for one thread at a time to manage them under most circumstances. This prevents them from being accessed by more than one thread simultaneously which can prevent difficult-to-track bugs.
In Swift, memory management is handled by Automatic Reference Counting (ARC). Whenever you create a new instance of a class ARC allocates a chunk of memory to store information about the type of instance and values of stored properties of that instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With