<aside> 🌻 只有类有析构器,枚举和结构体都没有,因为它们是值类型。
</aside>
每个类只能有一个析构器,且不接收任何参数,也没有小括号,后面直接接一个大括号,不能手动调用析构器!父类的析构器会被自动调用!
deinit {
// 执行析构过程
}
class Bank {
static var coinsInBank = 10_000
static func distribute(coins numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receive(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.distribute(coins: coins)
}
func win(coins: Int) {
coinsInPurse += Bank.distribute(coins: coins)
}
deinit {
Bank.receive(coins: coinsInPurse)
}
}
var playerOne: Player? = Player(coins: 100)
print("A new player has joined the game with \\(playerOne!.coinsInPurse) coins")
// 打印“A new player has joined the game with 100 coins”
print("There are now \\(Bank.coinsInBank) coins left in the bank")
// 打印“There are now 9900 coins left in the bank”
playerOne!.win(coins: 2_000)
print("PlayerOne won 2000 coins & now has \\(playerOne!.coinsInPurse) coins")
// 打印“PlayerOne won 2000 coins & now has 2100 coins”
print("The bank now only has \\(Bank.coinsInBank) coins left")
// 打印“The bank now only has 7900 coins left”
playerOne = nil
print("PlayerOne has left the game")
// 打印“PlayerOne has left the game”
print("The bank now has \\(Bank.coinsInBank) coins")
// 打印“The bank now has 10000 coins”