← Back to archive

Development · Swift

Understanding Swift inout parameters

Use inout to modify a caller’s variable and understand its copy-in, copy-out behavior.

Read the Korean original on Velog ↗English translation

Development archive cover

Changing a local copy of a value does not change the caller's variable. When a function needs to update that original variable, inout makes the intent explicit.

In-out parameters

Ordinary parameters do not let a function assign a new value to the caller's variable. Mark a parameter inout to allow changes made by the function to be written back to that variable.

var a = 2
var b = 3

func swapInt(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

swapInt(&a, &b) // a is 3, b is 2

At the call site, prefix the variable with & to pass it as an in-out argument.

Copy-in, copy-out

Swift describes in-out behavior using a copy-in, copy-out model:

  1. Read the argument's value when the function is called.
  2. Modify the parameter inside the function.
  3. Write the result back to the original variable when the function returns.

Further reading: Swift: In-Out Parameters.

← Back to archive