← 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.
Syntax
swift
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

markup
// 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)")

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
// 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)")
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
  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.