Swift Introduction | Functions | inout Arguments

Another Swift function feature to learn is the inout argument. This special argument lets a function modify the argument itself. Add inout before the argument.

(inout argumentName:Type)

When passing a variable to an inout argument, add & before the variable name. You cannot pass a literal because a literal cannot be modified.

The following is an example of an inout argument.

func tax(inout price:Int, rate:Double = 0.08) -> Void {
    price = Int(Double(price) * (1.0 + rate))
}

var num = 12300
tax(&num)

The function is declared as follows.

tax(inout price:Int, rate:Double = 0.08)

The first argument, price, is an inout argument. The return type is Void. The function call is as follows.

tax(&num)

This directly changes the value of num. Functions usually return values, but an inout argument lets a function modify the value stored in a variable directly.