Swift: Pass an array by reference?


In Swift, you can pass an array by reference in a function as an argument using inout keyword. In Swift, arrays are value types by default. In other words, they pass a value rather than a reference. If you pass an array to a function as an argument, it makes a copy and passes that copy to the function.

First, let's understand what happens when we pass an array in a function as a value.

func passByValue(_ array: [Int]) {
   array.append(100)
}
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
passByValue(numbers)

When you run the above code, you will get an error like the one below −

error: cannot use mutating member on immutable value: 'array' is a 'let' constant

There is no doubt that this error will occur. You can see the argument array is a constant by default when it is passed to a function.

However, if you want to pass an array by reference, you can use the inout parameter in Swift. The input parameter allows you to pass a value as a reference instead of a copy of its value.

Step 1 − In this example, we have created a passByReference function that will take an inout parameter named array.

Step 2 − This array is a reference to the original array passed as an argument.

Step 3 − The function appends the value 100 to the end of the array, and when the function returns, the original array has been modified.

Step 4 − To pass an array by reference using an inout parameter, you must prefix the parameter name with an ampersand (&) when calling the function.

Example

Here is an example of passing an array by reference −

func passByReference(_ array: inout [Int]) {
   array.append(100)
}
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Original array: \(numbers)")
passByReference(&numbers)
print("Modified array: \(numbers)")

Output

Original array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Modified array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]

Example

Here is another example of passing by reference

func passByReference(_ array: inout [Int]) {
   array = array.map { element in element + 1 }
}
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Original array: \(numbers)") // print: Original array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
passByReference(&numbers)
print("Modified array: \(numbers)") // print: Modified array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output

Original array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Modified array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Conclusion

Arrays are valued by default and passed by value in Swift. In other words, when you pass an array to a function, the array copies itself and sends the copy to the function. Whatever changes you make inside the function will not reflect the original array.

To pass an array by reference you can use the input parameter. This allows you to modify the argument in memory. It will reflect the original array outside the function.

Updated on: 11-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements