swift - When should I use deinit? -
i came across function called deinit()
while reading programming guide, i'm still wondering why , when need implement since don't need manage memory.
regards.
it's not required implement method, can use if need action or cleanup before deallocating object.
the apple docs include 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 player removed game, coins returned bank.
Comments
Post a Comment