Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use inout Parameters in Swift
Written by Team Kodeco

In Swift, function parameters are constants by default. This means that the values of the parameters passed to a function cannot be modified within the function. However, there may be cases where you want to modify the values of the parameters passed to a function. This is where inout parameters come in.

Inout parameters allow you to pass variables by reference, so that the function can modify the original variable. To declare an inout parameter, use the inout keyword before the parameter name.

For example, the following function takes two integers as inout parameters and swaps their values:

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

To pass an inout parameter, you need to use the & symbol before the variable name when calling the function.

var x = 5
var y = 10
swapNumbers(a: &x, b: &y)
print(x) // 10
print(y) // 5

In this example, the values of x and y are swapped.

Note: inout parameters can only be used with variable parameters, not constants or literals. Also, inout parameters cannot have default values and variadic parameters cannot be inout.

© 2024 Kodeco Inc.