Swift: What Are Inout Parameters?

In Swift, inout parameters allow you to change an input passed into a function.

For instance, let’s create a function that changes the original value of a number variable:

func change(_ number: inout Int){
    number = 2
}

var number = 1
change(&number)

print(number)

In this guide, you learn why inout parameters are needed in Swift and how they work.

Swift Function Parameters Cannot Be Changed

In Swift, changing the value of a parameter passed into a function is not possible. This is because a function argument is a constant, and constants cannot be modified.

For example:

func change(_ number: Int){
    number = 2
}

var number = 1
change(number)

print(number)

This results in an error:

main.swift:6:5: error: cannot assign to value: 'number' is a 'let' constant

This error says exactly what I told you above. You cannot modify a constant.

However, oftentimes it can be useful if you can change the parameter passed into a function.

As it turns out, this is possible by using inout parameters in Swift.

Inout Parameters in Swift

An inout parameter is a special type of parameter that can be modified inside a function and the changes apply outside the function.

Here is an illustration of a function that takes a number A as an inout parameter and modifies it:

To turn a function parameter into an inout variable that can be changed inside a function:

  1. Change the parameter to an inout parameter using the inout keyword modifier.
  2. Use & when passing an argument into the function call.

Example

For instance, let’s write a function that takes an argument that gets updated in the function:

func change(_ number: inout Int){
    number = 2
}

var number = 1
change(&number)

print(number)

Output:

2

As you can see, we change the number input inside the function, but the change is visible outside the function as well.

Conclusion

Swift inout parameter is a parameter that can be changed inside the function where it’s passed into.

  • To accept inout parameters, use the inout keyword in front of an argument.
  • To pass a variable as an inout parameter, use the & operator in front of the parameter.

Thanks for reading.

Happy coding!

Further Reading

iOS Development Tips

Useful Swift Tips



Leave a Comment

Your email address will not be published.