2

Here is a code example from Swift Programming Book by Apple (in chapter: Deinitializers)

struct Bank {
    static var coinsInBank = 10_000
    static func vendCoins(coins: Int)-> Int {
        var coinsToVend = min(coins, coinsInBank)
        coinsInBank -= coinsToVend
        return coinsToVend
    }
    static func receiveCoins(coins: Int){
        coinsInBank += coins
    }
}

class MyPlayer {
    var coinsInPurse: Int
    init(coins: Int){
        coinsInPurse = Bank.vendCoins(coins)
    }
    func winCoins(coins: Int){
        coinsInPurse += Bank.vendCoins(coins)
    }
    deinit {
        Bank.receiveCoins(coinsInPurse)
        println("Bank has \(Bank.coinsInBank) coins")
    }
}

var playerOne: MyPlayer? = MyPlayer(coins: 250)
playerOne?.winCoins(100)
println("PlayerOne has \(playerOne!.coinsInPurse) coins")
println("Bank has \(Bank.coinsInBank) coins")
playerOne = nil
println("Bank has \(Bank.coinsInBank) coins")  //This prints 9650
                                               //instead of 10000

It appears the deinit method is not being invoked. Why?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Tushar
  • 3,022
  • 2
  • 26
  • 26
  • 2
    This is normal in case you are using playground as Memory management work bit different there. Have you tried in compiled app? – Kirsteins Mar 24 '15 at 13:28
  • Right @Kirsteins, it works correctly in compiled app but not in playground. – Tushar Mar 25 '15 at 05:53

1 Answers1

1

If you are trying this in an Xcode 6.1 (and possibly 6.2, I don't have it installed) playground, you'll see this behavior because playgrounds sometimes do extra retains you weren't aware of. If you paste this code into a scratch Swift console application in 6.1.1 it works correctly and prints 10000.

In the latest Xcode beta (6.3) this code works as expected even in a playground.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118