Introduction
There are times when we need to update the arguments we passed into a function in programming. Swift, on the other hand, does not allow us to modify function arguments because they are set to be constant by default. We'll get a compile-time error if we try to change function arguments within the function's body. It's a form of security that prevents us from changing the parameters by accident.
Let us understand why we need to use the inout parameter in swift using a small example.
Code
var x = 4
func makeDouble(num: Int) -> Int{
return num*2
}
print("The older value of x is:",x)
var y = makeDouble(num: x)
print("The newer value of x & y is:",x,",",y)
Output
The older value of x is: 4
The newer value of x & y is: 4 , 8
In the above code, we can see that the makeDouble() function takes an integer as an argument and returns the number by doubling its value. But actually, the value of x is not doubled. What if we have to make a function that actually doubles the value of x. Normally, we would do the following thing.
func makeDouble(num: Int) -> Int{
num*=2;
return num
}
But the above function will give the following error.
main.swift:4:8: error: left side of mutating operator isn't mutable: 'num' is a 'let' constant
num*=2;
~~~^
To overcome this problem, we use inout parameters.
inout Parameters
Consider the above scenario: we have a function that accepts an integer as a parameter, and we wish to change the double the value of that parameter. These changes must also be reflected outside of the function. We can use in-out parameters in such cases. It signifies that the parameter's value is supplied into the function and then returned to replace the original value of the parameters. In-out parameters use the same syntax as the previous code, with the exception that we must explicitly mention the "inout" keyword just before the data type, and we must use an ampersand(&) before the arguments when invoking the function. The ampersand(&) tells the compiler that we wish to change these values within the function. Another purpose for utilizing the ampersand (&) is that rather than producing duplicates, we want to utilize an alias for the current arguments.
The above programme will be modified in the following manner.
Code
var x = 4
func makeDouble(num: inout Int) {
num*=2;
}
print("The older value of x is:",x)
makeDouble(num: &x)
print("The newer value of x is:",x)
Output
The older value of x is: 4
The newer value of x is: 8
As we can see that the value of x changes after passing through the makeDouble() function.