0
0
Swiftprogramming~5 mins

In-out parameters for mutation in Swift

Choose your learning style9 modes available
Introduction

In-out parameters let a function change the value of a variable you pass in. This helps when you want the function to update something directly.

When you want a function to change a variable's value outside the function.
When you need to update multiple values inside a function and keep the changes.
When you want to avoid returning a new value and instead modify the original variable.
When you want to swap two values using a function.
When you want to increment or adjust a variable inside a function.
Syntax
Swift
func functionName(parameterName: inout Type) {
    // code that changes parameterName
}

// Calling the function:
functionName(&variable)

Use inout before the parameter type to allow mutation.

Use & before the variable name when calling the function to pass it as in-out.

Examples
This function doubles the value of myNumber by changing it inside the function.
Swift
func doubleValue(number: inout Int) {
    number = number * 2
}

var myNumber = 10
doubleValue(&myNumber)
print(myNumber)
This function swaps two integer values by mutating both parameters.
Swift
func swapValues(a: inout Int, b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var x = 5
var y = 10
swapValues(&x, &y)
print("x = \(x), y = \(y)")
Sample Program

This program shows how the increment function changes the original count variable by adding 1.

Swift
func increment(value: inout Int) {
    value += 1
}

var count = 7
print("Before increment: \(count)")
increment(&count)
print("After increment: \(count)")
OutputSuccess
Important Notes

You must use & when passing a variable to an in-out parameter.

Constants and literals cannot be passed as in-out parameters because they cannot be changed.

In-out parameters are useful for modifying variables without returning new values.

Summary

In-out parameters let functions change variables passed to them.

Use inout in the function and & when calling.

This helps update values directly and keep changes after the function ends.