当前位置: 首页 > 编程学习 > 其它语言 > Swift > 正文

Swift4 反初始化,例子代码

2018-04-22 来源:博客园/CC_Joy

反初始化

苹果官方指南 Deinitialization

苹果官方指南翻译 反初始化

反初始化器原理

类实例被释放时,反初始化器就会立即被调用。关键字为 deinit

deinit{
    // perfrom the deinitialization
}

不能自行调用。父类的反初始化器可以被继承,子类反初始化器结束后父类的会被调用。父类总被调用,无论子类有无反初始化器。反初始化器可访问实例中所有属性,并可以基于属性修改自身行为。

反初始化器应用

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 = 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"