In the âpart 7 - breaking Cyclesâ dealing with the example of the âGalileoâ supernova, I understood that âunownedâ isnât the solution because the variable was already deallocated before accessing it in the closure.
I took the provided final sample and after commenting the whole âKeplerâ example, there was no error anymore: âinit Galileoâ and âdeinit Galileoâ are indicated in the debug area.
I donât understand why this happens because we are in the same configuration of a deallocated variable before accessing.
Would you mind explaining why this occurs, please ?
I understood this error.
Now, I comment the âTychoâ and the âKeplerâ parts while adding a âstartâ and âendâ as follows:
do {
let galileo = Supernova("Galileo")
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1 ) { [unowned galileo] in
print("Start")
galileo.explode()
print(galileo.name)
print("End")
}
}
I thought I should get the same result but, instead, I got:
đŁ init Galileo
â ď¸ deinit Galileo
Start
No error anymore (weird) and the end of the queue isnât reached (normal).
I donât know why thereâs no error while the Galileo variable is clearly deallocated and isnât checked as nil contrary to the âweakâ case.
Any ideas ?
Ah, I see. This looks like it a problem with the playground.
What I think is happening is that the playground is shutting down and swallowing the trap. You would see the proper behavior if you built in a project instead of a playground I believe. (I was hoping that the line PlaygroundPage.current.needsIndefiniteExecution = true would have fixed this but apparently does not.)
Another way you can see a trap is to just add this to the end of the playground.
Thread.sleep(forTimeInterval: 1)
You will see a crash if you using [unowned galileo] and it will go away if you use the other version.
In short, I think your understanding is correct and the strange behavior is just the playground trying to be âextra helpful.â
Youâre right, the playground is the problem.
I created a blank project and everything works fine as expected.
In the end, let me emphasize the quality of this tutorial that really helped me to understand notions I used without really knowing what was under the hood.
Just a little point to finish: in the âpart 4 - Challenge: Fix the Leak 1â, the provided solution in the sample code doesnât match the video.
Itâs definitely not a problem but itâs just to have more consistency between these two explanations unless itâs been made on purpose (the second one is more elegant ).
Thanks for pointing that out. I created a final playground before filming and then film the playground. Most of the time they are exactly the same and it doesnât matter which one gets copied in but in this case there was a difference. (As you say, it is sort of a peripheral difference, but still it would be better if they matched.)