Swift: What Are Inout Parameters?

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

As you may know, changing the value of a parameter passed into a function is not possible, as they are constants.

For example, this code refuses to compile:

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

var number = 1
change(number)

However, sometimes it is really useful when you can directly change the parameter passed into a function. But how can you do it if it is not possible the way I did it above?

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

For example:

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

var number = 1
change(&number)

print(number)

Output:

2

Now if you examine the example a bit closer, please pay attention to these two things:

  • The number parameter is of type inout Int. This makes it possible to modify it inside the function.
  • When you call the change function, you need to use & in front of the variable name: change(&number). This indicates that the variable can be modified by the function.

Conclusion

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

Thanks for reading. I hope you find these tips useful. Feel free to share the tips with anyone.

Here is a video version of the guide too:

Further Reading

iOS Development Tips

Useful Swift Tips



Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

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