Deconstruction of the Swift tutorials _swift

Source: Internet
Author: User

Destructors are invoked before an instance of a class is disposed. A destructor is defined with the keyword Deinit, similar to that of the initialization function, which is defined with INIT. Destructors apply only to class types.

1. Principles of the process of destructor

Swift will automatically release instances that are no longer needed to free resources. As described in the chapter on automatic reference counting, Swift handles memory management of instances through automatic reference counting (ARC). Usually you do not need to manually clean your instance when it is released. However, when using 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 might want to close the file before the class instance is released.

In the definition of a class, there can be at most one destructor for each class. The destructor does not take any arguments and is not written with parentheses:

Copy Code code as follows:

Deinit {
Perform the destructor process
}

A destructor is invoked automatically the first step before the instance release occurs. Unsolicited calls to its destructor are not allowed. The subclass inherits the destructor of the parent class, and the destructor of the parent class is invoked automatically at the end of the subclass destructor implementation. The destructor of the parent class is always invoked, even if the subclass does not provide its own destructor.

Because the instance is freed until the instance's destructor is invoked, the destructor can access the properties of all request instances, and can modify its behavior based on those properties (for example, to find the name of a file that needs to be closed).

2. destructor operation

Here is an example of a destructor operation. This example is a simple game that defines two new types of 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 properties and static methods to store and manage its current state.

Copy Code code as follows:

struct Bank {
static var Coinsinbank = 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 according to its coinsinbank properties. The bank also provides two methods--vendcoins and receivecoins--to handle the distribution and collection of coins.

The Vendcoins method checks to see if there are enough coins before the bank distributes the coins. If there are not enough coins, the bank returns a number smaller than the request (returns 0 if no coins remain in the bank). The Vendcoins method declaration numberofcoinstovend as a variable parameter so that you can modify the number 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 only adds the number of coins stored and received by the bank, and then 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 given time. This is reflected by the player's Coinsinpurse attribute:

Copy Code code as follows:

Class Player {
var coinsinpurse:int
Init (coins:int) {
Coinsinpurse = bank.vendcoins (coins)
}
Func Wincoins (coins:int) {
Coinsinpurse + + bank.vendcoins (coins)
}
Deinit {
Bank.receivecoins (Coinsinpurse)
}
}

Each player instance is initialized with a specified number of coins, which are obtained during bank initialization. If there are not enough coins available, the player instance may receive less than the specified number of coins.

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 a destructor that is invoked one step before the player instance is released. The destructor here simply returns all of the player's coins to the bank:

Copy Code code as follows:

var playerone:player? = Player (coins:100)
println ("A new player has joined" game with playerone!. Coinsinpurse) Coins ")
Output "A new player has joined the game with coins"
println ("There are now (Bank.coinsinbank) coins left in the Bank")
Output "There are now 9900 coins left in the bank"

A new player instance is created with a 100-coin (if any) request. This player instance is stored in an optional player variable named Playerone. An optional variable is used here because the player can leave the game at any time. Set to optional so you can track whether there is currently a player in the game.

Because the playerone is optional, it is decorated with an exclamation point (!), and whenever its Wincoins method is invoked, the Coinsinpurse property is accessed and the number of its default coins is printed.

Copy Code code as follows:

playerone!. Wincoins (2_000)
println ("Playerone won coins & now has" (playerone!. Coinsinpurse) Coins ")
Output "Playerone won Coins & now has 2100 coins"
println ("The Bank now has (Bank.coinsinbank) coins left")
Output "The bank now A has 7900 coins left"

Here, the player has won 2,000 coins. Player's wallet now has 2,100 coins, and the bank only has 7,900 coins left.

Copy Code code as follows:

Playerone = Nil
println ("Playerone has left the game")
Output "Playerone has left the game"
println ("The Bank now has (Bank.coinsinbank) coins")
Output "The bank now has 10000 coins"

The player has now left the game. This indicates that the optional Playerone variable is set to nil, meaning "no player instance". When this happens, the Playerone variable's reference to the player instance is corrupted. No other attribute or variable refers to the player instance, so it frees up the memory it occupies. Before this occurs, its destructor is invoked automatically, and its coins are returned to the bank.

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.