Junior — Middle
Could you explain the concept of Inout and how it is used in programming?
sobes.tech AI
Answer from AI
In Swift, inout is a keyword that allows a function to modify the value of a passed variable directly, rather than just working with its copy. Usually, function parameters are passed by value, meaning the function receives a copy, and changes inside the function do not affect the original. With inout, the function receives a reference to the variable, and changes inside the function are preserved after its execution.
Example usage:
func increment(value: inout Int) {
value += 1
}
var number = 5
increment(value: &number) // Passing with &
print(number) // Will output 6
Here, number is modified inside the increment function thanks to inout. This is convenient when you need to change multiple values in a function without returning new values.