I feel a bit lost using swift inout parameter in the following code:
var shouldContinue: Bool = true
func doSomeWork1(shouldContinue: inout Bool)
{
while shouldContinue
{
// ERROR: the compiler wants: doSomeWork2(shouldContinue: &shouldContinue)
doSomeWork2(shouldContinue: shouldContinue)
}
}
func doSomeWork2(shouldContinue: inout Bool)
{
while shouldContinue
{
}
}
Why does the compiler want doSomeWork2(shouldContinue: &shouldContinue)
instead of the compiler wants: doSomeWork2(shouldContinue: shouldContinue)
? isn't shouldContinue
already a pointer in the scope of doSomeWork1() ???
Being a pointer is only side-effect of optimization process for inout parameters. They actually work in different manner using copy-in copy-out behavior. So inside function that parameter is treated just like regular variable, not pointer. If you pass it to another function that takes inout parameter you have to mark it as such.
In-out parameters are passed as follows:
When the function is called, the value of the argument is copied.
In the body of the function, the copy is modified.
When the function returns, the copy’s value is assigned to the original argument.
This behavior is known as copy-in copy-out or call by value result. For example, when a computed property or a property with observers is passed as an in-out parameter, its getter is called as part of the function call and its setter is called as part of the function return.
As an optimization, when the argument is a value stored at a physical address in memory, the same memory location is used both inside and outside the function body. The optimized behavior is known as call by reference; it satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying. Write your code using the model given by copy-in copy-out, without depending on the call-by-reference optimization, so that it behaves correctly with or without the optimization.