在释放类实例之前立即调用析构器。使用deinit关键字编写析构器,类似于使用init关键字编写构造器。析构器只在class上可用。
1.析构器的工作原理
- Swift通过自动引用计数ARC处理实例的内存管理;
- 每个类最多只能有一个析构器。析构器不带任何参数,而且没有括号:
deinit {
// perform the deinitialization
}
- 在一个实例被释放前,系统会自动调用析构器。不允许自己手动调用析构器。
- 超类的析构器被它们的子类继承,超类的析构器会在子类析构器的实现末尾被自动调用。
- 即使子类没有实现自己析构器方法,超类的析构器方法也会被调用。
- 实例在调用析构器之后才被释放,所以在析构器中可以访问它所调用实例的所有属性,并可以根据这些属性修改其行为。
2.析构器的应用
下面是一个析构器的应用示例:
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")
// Prints "A new player has joined the game with 100 coins"
print("There are now \(Bank.coinsInBank) coins left in the bank")
// Prints "There are now 9900 coins left in the bank"
playerOne!.win(coins: 2_000)
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
// Prints "PlayerOne won 2000 coins & now has 2100 coins"
print("The bank now only has \(Bank.coinsInBank) coins left")
// Prints "The bank now only has 7900 coins left"
playerOne = nil
print("PlayerOne has left the game")
// Prints "PlayerOne has left the game"
print("The bank now has \(Bank.coinsInBank) coins")
// Prints "The bank now has 10000 coins"
网友评论