0

I incurred a small problem to solve retain cycle in Swift 4. (the same code works fine in swift 3) what do i miss please?

class User {
    weak var device:Device?
    init() {
        print("User allocated")
    }
    deinit {
        print("User deallocated")
    }
}

class Device {
    weak var user:User?
    init() {
        print("Device allocated")
    }
    deinit {
        print("Device deallocated")
    }
}


var user:User! = User();
var device:Device! = Device()
user.device = device;
device.user = user
user = nil;
device = nil

the output is :

User allocated
Device allocated

without no one of deallocated message.

Why? Thanks for your help.

Rebecca
  • 653
  • 6
  • 14
  • Device is holding the user non-weakly and the user is also on the device. This is by definition a retain cycle. Why not either not make a cycle to begin with or hold user weakly? – Benjamin Gruenbaum Mar 31 '19 at 20:01
  • even if i add weak on user in device class, the output is the same, im trying to prepare course about retain cycle and i do not understand why i can see deallocated output (please run my code on playground..) – Rebecca Mar 31 '19 at 20:10
  • 1
    You’re using a playground. Try it in an app and it will work fine. – Rob Mar 31 '19 at 20:13
  • 2
    This issues caused by playground https://stackoverflow.com/a/24363716/7451007 – Nikita Haiko Mar 31 '19 at 20:13
  • Thank you, last year it worked on playground with Swift 3 – Rebecca Apr 01 '19 at 08:27

0 Answers0