2

I have the following dummy class:

class Test {
    var value: String

    init(value: String) {
       self.value = value
    }

    deinit {
        print("deinit!")
    }
}

And I have the following code in a Swift Playground:

var strongReference: Test? = Test(value: "test")
weak var variable: Test!
variable = strongReference
strongReference = nil
print(variable.value)

This code actually works and prints "Test" and after that "deinit!". This comes as a surprise for me because I was expecting a crash in this situation. Even more stranger, the following code actually generates the crash I was looking for:

var strongReference: Test? = Test(value: "test")
weak var variable: Test! = strongReference
strongReference = nil
print(variable.value)

Anyone knows why is this happening?

Hamish
  • 78,605
  • 19
  • 187
  • 280
vbgd
  • 1,937
  • 1
  • 13
  • 18
  • 1
    Don't trust playgrounds – they're super buggy and unreliable. Try it in a real project and you'll see it works as expected (crashes and burns). – Hamish Mar 14 '17 at 10:42
  • Yes, you are right. It crashed in a real project. This is so sad because Playgrounds are so cool. – vbgd Mar 14 '17 at 10:45
  • Related questions: http://stackoverflow.com/q/24363384/2976878 & http://stackoverflow.com/questions/24021340/memory-leaks-in-the-swift-playground-deinit-not-called-consistently & http://stackoverflow.com/q/26091862/2976878 – Hamish Mar 14 '17 at 10:47

0 Answers0