The destructor is called immediately before an instance of a class is released. Use keywords Swift automatically releases instances that are no longer needed to release resources. Swift handles memory management of instances through automatic reference counting (ARC). Usually you don’t need to clean up manually when your instance is released. However, you may need to do some extra cleanup when using your own resources. For example, if you create a custom class to open a file and write some data, you may need to close the file before the class instance is released. In the definition of a class, there can be at most one destructor per class.The destructor takes no parameters and is written without parentheses: The output of the above program execution is as follows: When The output of the above program execution is as follows: deinit to mark the destructor, similar to the initialization function using the init to mark. Destructors apply only to class types. 9.38.1. Principle of destructing process #
9.38.2. Grammar #
deinit { // Execute the deconstruction process }
9.38.3. Example #
var counter = 0; // reference counter class BaseClass { init() { counter += 1; } deinit { counter -= 1; } } var show: BaseClass? = BaseClass() print(counter) show = nil print(counter) 1 0
show = nil after the statement is executed, the calculator subtracts 1 show the occupied memory will be released.var counter = 0; // reference counter class BaseClass { init() { counter += 1; } deinit { counter -= 1; } } var show: BaseClass? = BaseClass() print(counter) print(counter) 1 1