Swift从入门到精通第十二篇 - 反初始化(析构过程) 初识

反初始化(析构过程)(学习笔记)

环境Xcode 11.0 beta4 swift 5.1

  • 反初始化(析构过程)
    • 类实例销毁之前会立即调用析构器,用关键字 deinit
  • 反初始化(析构过程)如何工作
    • Swift仍然使用ARC管理机制,大部分情况下实例销毁不用手动清理;但有些情况下需要自己做一些额外的操作在实例销毁前,此时要可在析构器里实现
    • 一个类至多只有一个析构器

      deinit {
          // perform the deinitialization
      }
    • 析构器是自动调用
    • 析构调用之后实例才会被销毁,所以在析构器中可以访问实例的所有属性,可以修改这些属性的行为

  • 析构器的运用

        // 示例程序
        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"

    [Swift从入门到精通]

上一篇:关于内存条的一些猜想


下一篇:Java实现单例模式