What is inout Parameter in Swift?
Apr 27, 2022By default, function parameters are constants/non-mutable and if you try to change the value of a function parameter from within the body of that function, it results in a compile-time error. Therefore, if you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
var number = 6
func doubleNumber(num: Int) -> Int {
return num * 2
}
print(doubleNumber(num: number))
// Prints 12
print(number)
// Prints 6
In the code written above you will find that neither the variable "number" ever changes nor the parameter "num" can be assigned some value or basically you can say, it's immutable.
But what if you want both variable number should get changed and parameter num should be mutable ?
Yes, you can make it possible by adding inout keyword right before the parameter’s type and have to place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function.
var number = 6
func doubleNumber(num: inout Int) -> Int {
num *= 2
return num
}
print(doubleNumber(num: &number))
//Prints 12
print(number)
//Prints 12
Now, the interesting thing here is not just the goal that you have achieved using inout keyword, but if you cmd + click on *= operator in function doubleNumber, and jump to it's definition you would find the most interesting part;
Yes, you got it!
*= behind the scenes has a static method which has a parameter lhs that includes inout keyword. So, when you using +=, *= & -= etc. the calculations are basically stored in the lhs parameter at the end.
Two thing that are important while you use inout param are, you can only use a variable to pass in the in-out type parameter not a let constant since is let constant is immutable, and in-out parameters can’t have default values.
What's next?
We're happy to help you understand the concept of Inout Parameters, but in swift, there are other important topics that you might have gone through or are remaining. So we encourage you to go over the concept of functions, arrays, or conditional statements.