Swift Learning Swift Programming Tour---destruction method (19)

Source: Internet
Author: User

A destructor is called immediately before the instance memory of a class is freed. Use the DEINIT keyword to declare the destructor method, similar to the constructor method declared with Init. The destructor method is only applicable to class types.

principle of the Destructor method  Swift frees up resources by automatically releasing instances that are no longer needed. As described in the Chapter automatic reference count, Swift handles memory management of instances by automatic reference counting (ARC). Do not need to be cleaned manually. 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 close the file before the class instance is freed. In the definition of a class, there can be at most one destructor method per class. The inverse initializes the function without any arguments, without parentheses on the notation:
deinit {    //  destructor }

The destructor method is called automatically before the instance release occurs. It is not allowed to actively invoke its own destructor method. The subclass inherits the destructor of the parent class, and at the end of the implementation of the subclass destructor method, the parent class's destructor is automatically called. The destructor of the parent class is always called, even if the subclass does not provide its own destructor method. Because the instance is not freed until the instance's destructor is called, the destructor can access the properties of all the request instances, and it can modify its behavior based on those properties (such as finding a file name that needs to be closed). destructor OperationHere is an example of how a destructor is manipulated. This example is a simple game that defines two new types, bank and player. The bank structure manages the flow of a virtual currency, in which the bank can never have more than 10,000 coins. There is only one bank in this game, so the bank is implemented by a struct with static attributes and static methods to store and manage its current state.
  Bank { static  var  Coinsinbank =< Span style= "color: #000000;" > 10_000  static  func vendcoins (var  numberofcoinstovend:int)-> Int {numberofcoinstovend  = min (numberofcoinstovend, Coinsinbank) coinsinbank -= numberofcoinstovend  return   Numberofcoinstovend}  static   Func Receivecoins (coins:int) {Coinsinbank  + =   Coins}}   

The bank tracks the current number of coins it owns based on its Coinsinbank property. The bank also provides two methods-vendcoins and receivecoins to handle the distribution and collection of coins. The Vendcoins method checks if there are enough coins before the bank distributes the coins. If there are not enough coins, the bank returns a number that is smaller than the request (returns 0 if no coin is left in the bank). The Vendcoins method declares numberofcoinstovend as a variable argument so that the number can be modified inside the method body without having to define a new variable. The Vendcoins method returns an integer value indicating the actual number of coins provided. The Receivecoins method simply adds the number of coins stored and received to the Bank and saves it back to the bank. The player class describes a player in the game. Each player has a certain number of coins stored in their wallets at any one time. This is illustrated by the player's Coinsinpurse property:
 class  Player {         var  coinsinpurse:int         init (coins:int) {              =  Bank.vendcoins (coins)         }          func wincoins (coins:int) {              + =  bank.vendcoins (coins)         }          Deinit {            bank.receivecoins (coinsinpurse)         }       }

Each player instance is initialized with a specified number of coins, which are obtained during the bank initialization process. If there are not enough coins available, the player instance may receive fewer coins than the specified number. The player class defines a Wincoins method that obtains a certain number of coins from the bank and adds them to the player's wallet. The player class also implements an inverse initialization function, which is called in the previous step of the player instance release. Here the inverse initialization function simply returns all the player's coins to the bank:
 var) println ("A new player has joined the game with \ (playerone!. coinsinpurse) Coins"//  output" A new     player has joined the gamewith the Printl N ("there is now \ (bank.coinsinbank) coins left    inthe Bank"// output "There is now 9900 coins left in the bank"

  A new player instance is created with a request for 100 coins (if any). This player instance is stored in an optional player variable named Playerone. An optional variable is used here because players can leave the game at any time. Set to optional so that you can track whether there is currently a player in the game.   Because Playerone is optional, so by an exclamation point (!) To decorate, whenever its Wincoins method is called, the Coinsinpurse property is accessed and prints out its default number of coins.
playerone! . Wincoins (2_000) println ("Playerone won" Coins & now have \    (playerone!. coinsinpurse) Coins"//println (" TheBank is only have\ ( Bank.coinsinbank) Coinsleft"//  Output" The bank now is only have 7900 coins left "

Here, the player has won 2,000 coins. The player's wallet now has 2,100 coins, and the bank has only 7,900 coins left.
Playerone = Nil println ("playeronehave left the game"//  println ("TheBank has \ (bank.coinsinbank) Coins"//

Player has now left the game. This indicates that you want to set the optional Playerone variable to nil, which means "there is no player instance." 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 and its coins are returned to the bank.

Swift Learning Swift Programming Tour---destruction method (19)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.