Swift Deinitialization
In Swift, deinitialization is the process of cleaning up an instance of a class or structure when it is no longer needed. Deinitializers are called automatically just before the instance is deallocated from memory. In contrast to initializers, Swift automatically provides a default deinitializer for classes that deallocates any resources that the instance has acquired.
Syntax
The syntax for a deinitializer is as follows:
1deinit { 2 // deinitialization code here 3}
The deinitializer does not take any parameters and is written with the deinit
keyword.
Example
Here's an example of a simple Person
class with a deinitializer that prints a message when the instance is deallocated:
1class Person { 2 var name: String 3 4 init(name: String) { 5 self.name = name 6 } 7 8 deinit { 9 print("\(name) is being deallocated") 10 } 11} 12 13// Create an instance of the class 14var person: Person? = Person(name: "Alice") 15 16// Deallocate the instance 17person = nil 18 19// Output: "Alice is being deallocated"
In the example, we create an instance of the Person
class and then set it to nil
, which triggers the deinitializer and prints a message to the console.