反初始化(析构过程)(学习笔记)
环境Xcode 11.0 beta4 swift 5.1
- 反初始化(析构过程)
- 反初始化(析构过程)如何工作
析构器的运用
// 示例程序 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!.win(coins: 2_000) print("PlayerOne won 2000 coins & Now has \(playerOne!.coinsInPurse) coins") // Prints "PlayerOne won 2000 coins & Now has 2100 coins" print("The bank Now only has \(Bank.coinsInBank) coins left") // Prints "The bank Now only has 7900 coins left" 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"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。