Oleg Gordiichuk Oleg Gordiichuk - 4 months ago 17
Swift Question

inout Declarations for Type Decoration

I have a question according usage of the

inout
in Swift 3.

As i understand
inout
is quite expensive operation for use.

And there is question when and why it is better to use
inout
declaration?

regular function:

func double(input: Int) {
var input = input
input = input * 2
}


inout
declaration use:

func double(input: inout Int) {
input = input * 2
}

Answer

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.