What if your functions could change your data instantly without extra hassle?
Why In-out parameters for mutation in Swift? - Purpose & Use Cases
Imagine you have a list of numbers and you want to double each number by writing a function. Without in-out parameters, you have to return a new list and replace the old one manually every time.
This manual way is slow and error-prone because you must remember to assign the returned value back. If you forget, your original data stays unchanged, causing bugs that are hard to find.
In-out parameters let you pass a variable to a function and let the function change it directly. This means you don't have to return and reassign; the original variable updates automatically, making your code cleaner and safer.
func double(numbers: [Int]) -> [Int] {
var result = [Int]()
for n in numbers {
result.append(n * 2)
}
return result
}
var myNumbers = [1, 2, 3]
myNumbers = double(numbers: myNumbers)func double(numbers: inout [Int]) {
for i in 0..<numbers.count {
numbers[i] *= 2
}
}
var myNumbers = [1, 2, 3]
double(numbers: &myNumbers)This lets you write functions that directly change your data, making your code simpler and less error-prone.
Think about a game where you want to update a player's score inside a function. Using in-out parameters, you can pass the score variable and update it directly without returning and reassigning.
Manual data changes need extra steps and can cause bugs.
In-out parameters let functions change variables directly.
This makes code cleaner, safer, and easier to read.