Swift destructing process
The destructor is called immediately before an instance of a class is released. Use keywords deinit
to mark the destructor, similar to the initialization function using the init
to mark. Destructors apply only to class types.
Principle of destructing process
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.
Grammar
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:
deinit {
// Execute the deconstruction process
}
Example
var counter = 0; // reference counter
class BaseClass {
init() {
counter += 1;
}
deinit {
counter -= 1;
}
}
var show: BaseClass? = BaseClass()
print(counter)
show = nil
print(counter)
The output of the above program execution is as follows:
1
0
When 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)
The output of the above program execution is as follows:
1
1