Swift Language Functions Inout Parameters


Functions can modify the parameters passed to them if they are marked with the inout keyword. When passing an inout parameter to a function, the caller must add a & to the variable being passed.

func updateFruit(fruit: inout Int) {
    fruit -= 1

var apples = 30 // Prints "There's 30 apples"
print("There's \(apples) apples")

updateFruit(fruit: &apples)

print("There's now \(apples) apples") // Prints "There's 29 apples".

This allows reference semantics to be applied to types which would normally have value semantics.