When should I use deinit?

后端 未结 6 1407
谎友^
谎友^ 2020-12-08 06:55

I came across a function called deinit() while reading The Swift Programming Language guide, but I\'m still wondering why and when we need to implement it since

6条回答
  •  独厮守ぢ
    2020-12-08 07:31

    It's not required that you implement that method, but you can use it if you need to do some action or cleanup before deallocating the object.

    The Apple docs include an example:

    struct Bank {
        static var coinsInBank = 10_000
        static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
            numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
            coinsInBank -= numberOfCoinsToVend
            return numberOfCoinsToVend
        }
        static func receiveCoins(coins: Int) {
            coinsInBank += coins
        }
    }
    
    class Player {
        var coinsInPurse: Int
        init(coins: Int) {
            coinsInPurse = Bank.vendCoins(coins)
        }
        func winCoins(coins: Int) {
            coinsInPurse += Bank.vendCoins(coins)
        }
        deinit {
            Bank.receiveCoins(coinsInPurse)
        }
    }
    

    So whenever the player is removed from the game, its coins are returned to the bank.

提交回复
热议问题