Introduction
To deallocate memory space before a class instance may be deallocated, the 'deinitializer' function must be used. To deallocate the memory areas held by system resources, use the phrase 'deinit.' Only class types are eligible for deinitialization.
When your instances are no longer needed, Swift 4 automatically deallocates them to free up resources. Automatic reference counting (ARC) is used in Swift 4 to manage memory for instances, as detailed in Automatic Reference Counting. When your instances are deallocated, you usually don't need to undertake any manual cleanup. When working with your resources, you may need to do some further cleanup yourself. If we develop a custom class to open and write data to a file, you may need to close the file before the class instance is deallocated.
When a class instance is no longer needed, the procedure of deinitialization is used. This reduces the amount of memory used by the system. To create a deinitializer, we utilize the deinit keyword.
Working
Swift frees up resources by automatically deallocating instances when they are no longer needed. Swift uses automatic reference counting (ARC) to manage instance memory, as detailed in Automatic Reference Counting. When your instances are deallocated, you usually don't need to undertake any manual cleanup. When working with your resources, you may need to do some further cleanup yourself. If we develop a custom class to open and write data to a file, you may need to close the file before the class instance is deallocated.
Each class declaration can only have one deinitializer. The deinitializer is written without parenthesis and takes no parameters:
deinit {
// perform the deinitialization
}
Just before instance deallocation, deinitializers are called automatically. You are not permitted to call a deinitializer. Subclasses inherit superclass deinitializers, and the superclass deinitializer is automatically invoked at the end of a subclass deinitializer implementation. Even if a subclass doesn't offer its deinitializer, superclass deinitializers are always called.
A deinitializer can access all attributes of the instance it's called on and adjust its behavior based on those properties because an instance isn't deallocated until after its deinitializer is run.