inout Parameters
An inout parameter lets a function reach into a variable from outside and actually change its value, not just look at it.
In this page:
Declaring an inout Parameter
Marking a parameter inout allows the function to modify the original variable passed in by the caller, rather than working on a copy.
Example: Declaring an inout Parameter
func doubleInPlace(_ number: inout Int) {
number *= 2
}
var value = 5
doubleInPlace(&value)
print("Doubled value: \(value)")
Login to try C/C++/Java/PHP code in the editor
Swapping Two Values
A classic use of inout is a function that swaps two variables' values directly, without returning a tuple.
Note: Swift's standard library already provides a built-in swap(_:_:) function that does exactly this.
Example: Swapping Two Values
func swapValues(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 1
var y = 2
swapValues(&x, &y)
print("x=\(x), y=\(y)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the
&symbol when passing a variable to aninoutparameter at the call site -- it's required to make the mutation explicit. - Trying to pass a
letconstant or a literal value as aninoutargument; only a mutable variable can be passed. - Assuming
inoutpasses a reference like in some other languages by default; in Swift it must be explicitly declared withinoutin the parameter list.
Chapter Summary
inoutbefore a parameter's type lets the function modify the caller's original variable.- Callers must prefix the argument with
&to acknowledge it may be mutated. - Only variables (
var), not constants or literals, can be passed asinoutarguments. inoutis useful for functions like swap that need to modify their inputs directly.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: