Easy Tutorial
❮ Swift Enumerations Swift Subscripts ❯

Swift Deinitialization

Before a class instance is deallocated, the deinitializer is called immediately. The deinitializer is marked with the keyword deinit, similar to how the initializer is marked with init. Deinitializers are only applicable to class types.


Deinitialization Principles

Swift automatically releases instances that are no longer needed to free up resources.

Swift manages memory for instances through Automatic Reference Counting (ARC).

Typically, you don't need to perform manual cleanup when your instances are deallocated. However, when using your own resources, you might 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 deallocated.

Syntax

Within the class definition, each class can have at most one deinitializer. The deinitializer does not take any parameters and is written without parentheses:

deinit {
    // Perform deinitialization
}

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 is:

1
0

When the statement show = nil is executed, the counter is decremented by 1, and the memory occupied by show is 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 is:

1
1
❮ Swift Enumerations Swift Subscripts ❯