In Swift, inout
is a keyword used to indicate that a parameter is passed by reference and can be modified inside a function, affecting the original value outside the function. This allows a function to modify the value of the parameter and have those changes reflected in the calling scope.
Here’s an example to illustrate the use of inout
:
func doubleInPlace(number: inout Int) {
number *= 2
}
var myNumber = 5
// Call the function with an inout parameter
doubleInPlace(number: &myNumber)
// The original value of myNumber has been modified
print(myNumber) // Output: 10
In this example:
- The
doubleInPlace
function takes aninout
parameter namednumber
of typeInt
. - When calling the function, the
&
(ampersand) symbol is used to indicate thatmyNumber
should be passed by reference. - Inside the function, the value of
number
is doubled, and this modification is reflected in the original variablemyNumber
outside the function.
It’s important to note that inout
parameters must be variables, not constants, and they cannot be used with literals or expressions directly. They are typically used when you need a function to modify the value of a parameter and have those changes persist outside the function.
// Incorrect usage (will result in a compiler error)
// doubleInPlace(number: 5) // Error: 'inout' argument must be a variable