Exchange array elements in Swift
I wrote a function to swap array elements. But it returns an error: Playground execution failed :: 21: 5: error: "@lvalue $ T8" is not identical to "T" data [i] = data [j] ^: 22: 5: error: '@lvalue $ T5 'is not identical to' T 'data [j] = temp ^
The code looks like this:
func exchange<T>(data: [T], i:Int, j:Int) {
let temp:T = data[i]
data[i] = data[j]
data[j] = temp
}
+3
source to share
2 answers
data
should be a parameter inout
:
func exchange<T>(inout data: [T], i:Int, j:Int) {
let temp:T = data[i]
data[i] = data[j]
data[j] = temp
}
You would call it like this:
var array = [1,2,3]
exchange(&array, 0, 2)
See output parameters in the quick programming guide.
+1
source to share