Swift destructs the process

The destructor is called immediately before an instance of a class is released. T he deinit marked with the keyword deinit, similar to the initialization function marked with init The destructor applies only to class types.


The principle of the destructing process

Swift automatically releases instances that you no longer need to free up resources.

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

Usually when your instance is released, you don't need to clean it up manually. 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 might need to close the file before the class instance is released.

Grammar

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

deinit {
    // 执行析构过程
}

Instance

var counter = 0;  // 引用计数器
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:

1
0

When the show-nil statement is executed, the calculator subtracts 1 and the memory consumed by show is freed.

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

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

var show: BaseClass? = BaseClass()

print(counter)
print(counter)

The output of the above program execution is:

1
1