I have a question according usage of the
inout
inout
inout
func double(input: Int) {
var input = input
input = input * 2
}
inout
func double(input: inout Int) {
input = input * 2
}
Be careful, this is a classic trap! :)
Your two functions are not doing the same thing, so one is not "better" than the other.
Your first one:
func double(input: Int) {
var input = input
input = input * 2
}
does nothing.
Because with var input = input
you are making a copy of the input value, so when you do input = input * 2
you are just modifying the local copy, and since you don't return it, it is discarded and this function has no effect in the end.
Your second one:
func double(input: inout Int) {
input = input * 2
}
does something: it modifies the original value because inout
is a way of passing a value by reference. No need to make a copy and return it: the variable itself, the one you pass to the function, will be changed.
Note: I suggest you read Martin R's excellent link where inout
is very well explained: http://stackoverflow.com/a/34486250/1187415.