What is inout parameter in swift?

By | January 24, 2024

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 an inout parameter named number of type Int.
  • When calling the function, the & (ampersand) symbol is used to indicate that myNumber should be passed by reference.
  • Inside the function, the value of number is doubled, and this modification is reflected in the original variable myNumber 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

Leave a Reply

Your email address will not be published. Required fields are marked *