ref – http://stackoverflow.com/questions/34486052/when-to-use-inout-parameters/34486250
inout means that modifying the local variable will also modify the passed-in parameters.
Without it, the passed-in parameters will remain the same value.
Trying to think of reference type when you are using inout and value type without using it.
You’ll see that when we use functions with inout parameter, we pass in address of the objects using ampersand (&).
This is because inout uses address of the incoming object. That way, when we make changes inside the function, it dereferences
the address of the object. This means it gets the value of the object at the address passed in, and when we make changes, THAT change
is permanent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func size(x:inout Int) { // Set out parameter. x = 10 } // Value equals 0. var x = 0 print(x) // Call size with inout argument. size(x: &x) // Now variable equals 10. print(x) |
1 2 3 4 5 6 7 8 |
func changeChar(char: inout Character) { char = "b" print(char) // b print("\(#function) inside of function: \(char1)"); // b } changeChar(char: &char1); print("\(#function) outside of function: \(char1)") |
By default, function parameters are declared let. This makes it constant, and does not allow you to change the values. You can simply use them inside the function.
Function parameters are constants by default
Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake.
As of Swift 3.0, you only have 2 choices. Use the default behavior where your variable parameters is let. Or use inout where it is used like a reference.
http://stackoverflow.com/questions/34400600/using-inout-keyword-is-the-parameter-passed-by-reference-or-by-copy-in-copy-out?noredirect=1&lq=1
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. Do not depend on the behavioral differences between copy-in copy-out and call by reference.