Swift: What Are Inout Parameters?

Swift inout parameters allow you to change an input passed into a function inside that function.

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, this piece of code does not run because you try to change the parameter in a function:

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

var number = 1
change(number)

But sometimes it can be useful if you could change the parameter passed into a function.

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

Inout Parameters in Swift

This is where inout parameters help: An inout parameter can be modified inside a function and the changes apply outside the function.

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

  1. Mark the parameter with inout.
  2. Use & when passing a parameter value 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, a change was made to the number input inside a function, but the change applies outside the function too.

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



Share this article with others:

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email

Learn these 10 tips to write professional code.

 

Make your coding life easier with these amazing command-line tools

 

Learn how to use latest advancements in AI to write faster.

 

Leave a Comment

Your email address will not be published.