Inout Parameter in Swift Explained
Let’s start this article with a question. How do you think will the code below compile or not?
If your answer is no — then you are right. This code will not compile because all parameters passed into a function are constants. But there is a way to change a parameter inside a function. And that is where we will need to introduce the inout
keyword.
In the present article, let’s cover the following questions:
- What is the
inout
keyword? - Why would you need to use it?
What is the inout keyword and how to use it
As I mentioned previously, all parameters passed into a function are constants. It means that you cannot change them inside a function. For that matter, you can find people copying a parameter’s value inside a function, modifying it, and then assigning its value to a global variable.
However, there is a special inout
keyword in Swift that allows us to pass parameters into a function, change them inside that function, and all changes will reflect the original value that was passed from outside that function. Hence the keyword inout
.
To start using it, first of all, you need to declare a variable, not a constant, but a variable, because it needs to be changed. After that, you need to use the inout
keyword between a parameter’s name and type. Consider the example below:
Lastly, when you want to use that function, you will have to use &
before the parameter, which is declared as an inout
parameter. You use that as the recognition that you are aware of it being used as inout
. Consider the following example:
How it works
Under the hood, Swift uses a technique called copy-in-copy-out
. When we call a function with an inout
parameter, it copies its value, then uses the copied value inside the function. And when the function returns, that copied value is assigned to the argument that was initially passed into the function.
Summary
All parameters passed into a function are constants, but you can change that behavior by introducing the inout
keyword. You use it when you need to change some value in place, rather than returning a new one.
Thanks for reading!
if you enjoyed this article, be sure to give it a clap so others will find it more easily.