Swift4 基礎(chǔ)部分: Deinitialization(析構(gòu)過程)

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

A deinitializer is called immediately before a class 
instance is deallocated. You write deinitializers with the 
deinit keyword, similar to how initializers are written 
with the init keyword. Deinitializers are only available 
on class types.
  • 在一個類的實例被釋放之前,析構(gòu)函數(shù)被立即調(diào)用。用關(guān)鍵字deinit來標(biāo)示析構(gòu)函數(shù),類似于初始化函數(shù)用init來標(biāo)示。析構(gòu)函數(shù)只適用于類類型。

例子:

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");
print("There are now \(Bank.coinsInBank) coins left in the bank");


playerOne!.win(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 only has \(Bank.coinsInBank) coins left");

執(zhí)行結(jié)果:

A new player has joined the game with 100 coins
There are now 9900 coins left in the bank
PlayerOne won 2000 coins & now has 2100 coins
The bank now only has 7900 coins left
PlayerOne has left the game
The bank now only has 10000 coins left
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容