这是 Apple 的 Swift Programming Book 中的一个代码示例(在章节:Deinitializers)
struct Bank {
static var coinsInBank = 10_000
static func vendCoins(coins: Int)-> Int {
var coinsToVend = min(coins, coinsInBank)
coinsInBank -= coinsToVend
return coinsToVend
}
static func receiveCoins(coins: Int){
coinsInBank += coins
}
}
class MyPlayer {
var coinsInPurse: Int
init(coins: Int){
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int){
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)
println("Bank has \(Bank.coinsInBank) coins")
}
}
var playerOne: MyPlayer? = MyPlayer(coins: 250)
playerOne?.winCoins(100)
println("PlayerOne has \(playerOne!.coinsInPurse) coins")
println("Bank has \(Bank.coinsInBank) coins")
playerOne = nil
println("Bank has \(Bank.coinsInBank) coins") //This prints 9650
//instead of 10000
似乎没有调用 deinit 方法。为什么?