析构器只适用于类类型,当一个类的实例被释放之前,析构器会被立即调用。析构器用关键字deinit来标示.
1.析构过程
- 析构器是在实例释放发生前被自动调用。
- 子类继承了父类的析构器,并且在子类析构器实现的最后,父类的析构器会被自动调用。
- 即使子类没有提供自己的析构器,父类的析构器也同样会被调用。
- 因为直到实例的析构器被调用后,实例才会被释放,所以析构器可以访问实例的所有属性。
- 语法:在类的定义中,每个类最多只能有一个析构器,而且析构器不带任何参数。
deinit { //执行析构过程 }
2.示例
//Bank类管理一种虚拟硬币,确保流通的硬币数量永远不可能超过 10,000。在游戏中有且只能有一个Bank存在 class Bank { static var coinsInBank = 10000; static func vendCoins(numberOfCoinsToVend: Int) -> Int { let retValue = min(numberOfCoinsToVend, coinsInBank); coinsInBank -= retValue; return retValue; } 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); } } var playerOne: Player? = Player(coins: 100); print("Player have (playerOne!.coinsInPurse) coins, Bank have (Bank.coinsInBank)"); //"Player have 100 coins, Bank have 9900 " playerOne?.winCoins(2000); print("Player have (playerOne!.coinsInPurse) coins, Bank have (Bank.coinsInBank)"); //"Player have 2100 coins, Bank have 7900 " playerOne = nil; print("Player have (playerOne?.coinsInPurse) coins, Bank have (Bank.coinsInBank)"); //"Player have nil coins, Bank have 10000 "