As a swift noob, and coming from C++, I wonder why the following prints 'BOOM!!':
var text = ""
class ArrayHandle {
var array = Array()
init() {
text = "success"
}
deinit {
text = "BOOM!!"
}
}
struct Array { var buffer = Buffer() }
struct Buffer { func doStuff() { print(text)} }
var buffer = ArrayHandle().array.buffer.doStuff()
Apparently the deinit is called before the text is printed...
When you change the code to:
var handle = ArrayHandle()
handle.array.buffer.doStuff()
it prints the expected 'success'
Is there a way to force developers to use a var to store an object, or is that just a hidden bug that may fail in the future?
If there is no exact control over the lifetime of an object in swift
There is.
When you declare a var or const, it remains referenced (and counted in ARC) as long as the block of its scope remains loaded.
For instance:
let handle = ArrayHandle()
if it is defined in a func, it stays referenced as long as you did not exit the func.
In a closure, as long you have not exited the closure (unless you declare the closure as escaping, then it survives after leaving.
In an if statement, as long as you are in the if statement.