Deinitialisers - RaduG/swift_learning GitHub Wiki

Overview

An object's deinitialiser is called before clearing up the memory for that object (0 reachable references). It does not take any parameters, does not return a value and it has access to all properties of the instance. Superclass deinitialisers are always called automatically.


class Bank {
  var funds: Int = 100

  func distribute(amount: Int) -> Int {
    let givenAmount = min(amount, funds)
    funds = funds - givenAmount
    return givenAmount
  }

  func cashIn(amount: Int) {
    print("Cashing in \(amount)")
    self.funds += amount
  }
}

class Player {
  var balance: Int
  let bank: Bank

  init?(bank: Bank, startAmount amount: Int) {
    self.bank = bank
    let balance = bank.distribute(amount: amount)

    guard balance == amount else {
      return nil
    }

    self.balance = balance
  }

  func spend(amount: Int) -> Bool {
    guard self.balance < amount else {
      return false
    }

    balance -= amount
    return true
  }

  deinit {
    bank.cashIn(amount: balance)
  }
}

let bank = Bank()
let player1 = Player(bank: bank, startAmount: 50)