Swift destruction process


The destructor is called immediately before an instance of a class is released. Use the keyword deinit to mark the destructor, similar to the way the initialization function is marked with init. Destructors only work on class types.


Principle of the destruction process

Swift will automatically release instances that are no longer needed to release resources.

Swift handles memory management of instances through automatic reference counting (ARC).

Usually there is no need to manually clean up when your instance is released. However, when using your own resources, you may need to do some additional cleanup.

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.

Syntax

In the definition of a class, each class can have at most one destructor. The destructor does not take any parameters and is written without parentheses:

deinit {
    // 执行析构过程
}

Example

var counter = 0;  // 引用计数器
class BaseClass {
    init() {
        counter++;
    }
    deinit {
        counter--;
    }
}

var show: BaseClass? = BaseClass()
print(counter)
show = nil
print(counter)

The output result of the above program execution is:

1
0

When the show = nil statement is executed Afterwards, the calculator subtracts 1, and the memory occupied by show will be released.

var counter = 0;  // 引用计数器

class BaseClass {
    init() {
        counter++;
    }
    
    deinit {
        counter--;
    }
}

var show: BaseClass? = BaseClass()

print(counter)
print(counter)

The output result of the execution of the above program is:

1
1