Fork me on GitHub

以撸代码的形式学习Swift-15:(类的)析构过程(Deinitialization)

1 析构过程原理

每个类最多只能有一个析构器,而且析构器不带任何参数

析构器是在实例释放发生前被自动调用。不能主动调用析构器。

子类继承了父类的析构器,并且在子类析构器实现的最后,父类的析构器会被自动调用。

2 析构器实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 以撸代码的形式学习Swift-15:(类的)析构过程(Deinitialization)
  • 本文作者: AndyRon
  • 发布时间: 2017年07月04日 - 13:42
  • 最后更新: 2018年10月15日 - 18:36
  • 本文链接: http://andyron.com/2017/swift-15-deinitialization.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!