← Back to Swift Course | Chapter 4: Functions | Lesson 5 of 7

inout Parameters

An inout parameter lets a function reach into a variable from outside and actually change its value, not just look at it.

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

markup
func doubleInPlace(_ number: inout Int) {
    number *= 2
}
var value = 5
doubleInPlace(&value)
print("Doubled value: \(value)")

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

markup
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)")
Common Mistakes
  1. Forgetting the & symbol when passing a variable to an inout parameter at the call site -- it's required to make the mutation explicit.
  2. Trying to pass a let constant or a literal value as an inout argument; only a mutable variable can be passed.
  3. Assuming inout passes a reference like in some other languages by default; in Swift it must be explicitly declared with inout in the parameter list.
Chapter Summary
  • inout before 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 as inout arguments.
  • inout is 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.