In and Out
By default, Swift’s function parameters are constant value types. This means that when a parameter is passed into a function, a copy of the value is created and passed to the function. Any modifications made to the parameter inside the function will not affect the original value outside the function.
However, we can use the inout
keyword to pass a parameter by reference instead of by value. When we use inout
, we are passing a reference to the original value, allowing modifications made inside the function to be reflected in the original value outside the function.
Example 1
Here’s an example to illustrate the power of inout
parameters in Swift:
1
2
3
4
5
6
7
func doubleValue(_ value: inout Int) {
value *= 2
}
var number = 5
doubleValue(&number)
print(number) // Output: 10
In this example, we define a function called doubleValue that takes an inout
parameter of type Int. When we call the function and pass in a value, the function doubles the value of the parameter directly, and that change is reflected in the original number
variable that is outside of the doubleValue function.
Example 2
Here’s another example:
1
2
3
4
5
6
7
8
9
10
11
func removeElement(_ element: Int, fromArray array: inout [Int]) {
if let index = array.firstIndex(of: element) {
array.remove(at: index)
}
}
var numbersArray = [1,2,3,4,5]
removeElement(2, fromArray: &numbersArray)
print(numbersArray) // prints [1,3,4,5]
In this example, we are passing an array of integers as an inout parameter. The removeElement function will search for a specific element in the array and remove it if found. The changes made to the array within the function will be reflected in the original numbersArray
variable that was passed to the function.
Conclusion
Using inout parameters can be incredibly useful as you can see, especially when working with complex data types like arrays or dictionaries. By passing these types as inout parameters, you can modify them directly inside a function, which can be much more efficient than copying the entire data structure every time we need to make a modification to them.
However, It’s still important to note that inout parameters should be used sparingly, as they can make code harder to reason about and debug. When you use inout parameters, you need to be careful to ensure that changes made to the parameter value inside the function do not cause unexpected side effects outside the function.
Note: Not all data types in Swift can be passed as inout parameters. Inout parameters are only allowed for variables that can be modified, such as variables declared with var. Constants declared with let cannot be passed as inout parameters. Additionally, some types, such as enums and tuples, cannot be modified and therefore cannot be passed as inout parameters.