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:
Syntax
func functionName(_ param: inout Type) {
param = newValue // changes the caller's variable
}
var variable = value
functionName(&variable)
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
// Define the function `doubleInPlace` taking `number`
func doubleInPlace(_ number: inout Int) {
number *= 2
}
// Declare a mutable variable `value`, initialized to `5`
var value = 5
doubleInPlace(&value)
// Print "Doubled value: \(value)" to the console
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
// Define the function `swapValues` taking `a`, `b`
func swapValues(_ a: inout Int, _ b: inout Int) {
// Declare a constant `temp`, set to `a`
let temp = a
a = b
b = temp
}
// Declare a mutable variable `x`, initialized to `1`
var x = 1
// Declare a mutable variable `y`, initialized to `2`
var y = 2
swapValues(&x, &y)
// Print "x=\(x), y=\(y)" to the console
print("x=\(x), y=\(y)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: