2

I would like to know about the flow of compilation in xcode's playground. I understand it will be same as done in Xcode but as per the output of playground its confusing.

import UIKit
// ARC
class Student {
    let name: String

    init(name: String) {
        self.name = name
        print("\(name) is being initialized")
    }

    deinit {
        print("\(name) is being deinitialized")
    }
}

var reference1: Student?
var reference2: Student?
var reference3: Student?

reference1 = Student(name: "John Appleseed")
reference2 = reference1
reference3 = reference1

reference1 = nil
reference2 = nil
reference3 = nil

//Strong reference cycle

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Clair")
unit4A = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john

john = nil
unit4A = nil

Output:-

John Appleseed is being initialized
John Clair is being deinitialized
Apartment 4A is being deinitialized
John Appleseed is being deinitialized

John Appleseed is being deinitialized

should print before

John Clair is being deinitialized

As reference3 = nil will call deinit method of class Student and John Appleseed is being deinitialized should get printed and after that john = nil will call deinit method of Person class and John Clair is being deinitialized should get printed

Note:- init method of class Person and Apartment is not printing anything in the above shown example

Apogee
  • 689
  • 8
  • 19
  • This works fine in ios app, may be you can file a bug for playground – Inder Kumar Rathore Nov 21 '17 at 12:15
  • Check [this](https://stackoverflow.com/questions/24363384/deinit-method-is-never-called-swift-playground) and [this](https://stackoverflow.com/questions/24021340/memory-leaks-in-the-swift-playground-deinit-not-called-consistently) – Puneet Sharma Nov 21 '17 at 12:15
  • @InderKumar thanks for the suggestion. I'll file a bug and post the answer here whenever get any response from apple. – Apogee Nov 21 '17 at 12:50

0 Answers0