1 析構(gòu)過程原理
每個(gè)類最多只能有一個(gè)析構(gòu)器,而且析構(gòu)器不帶任何參數(shù)
析構(gòu)器是在實(shí)例釋放發(fā)生前被自動(dòng)調(diào)用碘耳。不能主動(dòng)調(diào)用析構(gòu)器。
子類繼承了父類的析構(gòu)器,并且在子類析構(gòu)器實(shí)現(xiàn)的最后迫卢,父類的析構(gòu)器會(huì)被自動(dòng)調(diào)用。
2 析構(gòu)器實(shí)踐
class Bank {
static var coinsInBank = 10_000
static func vendCoins(numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(numberOfCoinsRequested: coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(numberOfCoinsRequested: coins)
}
deinit {
Bank.receiveCoins(coins: coinsInPurse)
}
}
var playerOne: Player? = Player(coins: 100)
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
print("There are now \(Bank.coinsInBank) coins left in the bank")
playerOne!.winCoins(coins: 2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
print("The bank now only has \(Bank.coinsInBank) coins left")
playerOne = nil
print("PlayerOne has left the game")
print("The bank now has \(Bank.coinsInBank) coins")
playground文件在andyRon/LearnSwift