0

I'm working my way through the Swift language reference, and am trying to understand how weak and unowned references are implemented. The code snippet below is in the book, except that I've added println() statements in the initializers as well. When I execute it, I get confirmation that the objects were initialized, but they don't deinitialize.

class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
        println("Customer init")
    }
    deinit { println("Customer deinit") } 
}

class CreditCard {
    let number: UInt64
    unowned let customer: Customer
    init (number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
        println("CreditCard init")
    }
    deinit { println("Card #\(number) deinit") } 
 }

var john: Customer?

john = Customer(name: "John Appleseed") 
john!.card = CreditCard(number: 540530453, customer: john!) 
john = nil

My console output is:

Customer init
CreditCard init

which means to me that the objects are initializing, but not deinitializing. Why is Swift holding on to the references and not letting the objects be destroyed?

  • Are you testing this in a Playground? See (for example) http://stackoverflow.com/questions/24363384/deinit-method-is-never-called-swift-playground. – When I run your code in a compiled app then all object are deallocated properly. – Martin R Mar 27 '15 at 21:05
  • Yes, I was testing in a Playground. I guess they're not foolproof. Thanks for the quick reply. – Steve Coan Mar 27 '15 at 21:07

0 Answers0