Destructors apply only to class types, and the destructor is called immediately before an instance of a class is disposed. The destructor is identified by the keyword Deinit, similar to the constructor used by Init.
Principle:
Swift frees up resources by automatically releasing instances that are no longer needed. Swift handles the memory management of the instance through an automatic reference count arc. Typically, you do not need to manually clean up your instances when they are released. However, when you use your own resources, you may need to do some extra cleanup. For example, if you create a custom class to open a file and write some data, you may need to manually close the file before the class instance is freed.
In the definition of a class, there can be at most one destructor per class, and the destructor has no parameters:
deinit{//performing the Destruction process}
The destructor is called automatically before the instance is released, and the destructor is not allowed to be invoked actively. Subclasses inherit the destructor of the parent class, and at the end of the subclass destructor implementation, the destructor of the parent class is automatically called. The destructor of the parent class is called even if the subclass does not provide its own destructor.
The instance is freed because the destructor of the instance is known to be called. So the destructor can access the properties of all the request instances, and it can modify its behavior based on those properties. For example, find a file that needs to be closed.
struct Bank { static var Coinsinbank = 10000 static func Vendcoins (Var numberofcoinstovend:int), int{ nu mberofcoinstovend = min (numberofcoinstovend,coinsinbank) Coinsinbank-= Numberofcoinstovend return Numberofcoinstovend } static func Receivecoins (coins:int) { Coinsinbank + = Coins }}class Player { var coinsinpurse:int init (coins:int) { coinsinpurse = bank.vendcoins (coins) } func Wincoins (coins:int) { coinsinpurse + bank.vendcoins (coins) } deinit{ bank.receivecoins ( Coinsinpurse) }}var playerone:player? = Player (coins:100) print (playerone!. Coinsinpurse) print (Bank.coinsinbank) playerone!. Wincoins (+) print (playerone!. Coinsinpurse) print (bank.coinsinbank) Playerone = Nilprint (Bank.coinsinbank) 10099001100890010000
Playerone is optional, so use an exclamation mark! To make modifiers.
When Playerone is nil, it means that there is no player instance, and when this happens, the Playerone variable's reference to the player instance is broken. There is no other property or variable that references the player instance, so it is freed in order to empty the memory it occupies. Before this occurs, its destructor is automatically called so that its coins are returned to the Bank object.
Swift-07-destructor Deinit