Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in Swift to know that struct is deleted from Memory?

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
like image 203
Aleksei Danilov Avatar asked Oct 20 '17 04:10

Aleksei Danilov


People also ask

Is Deinit () function available in structs?

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.

Where are structs stored Swift?

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).

Is struct thread safe in Swift?

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.

How does memory allocation work in Swift?

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.


1 Answers

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.

like image 104
Muhammad Aamir Ali Avatar answered Oct 24 '22 22:10

Muhammad Aamir Ali