I wrote a function to exchange the array elements. But it returns 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 is as follows:
func exchange<T>(data: [T], i:Int, j:Int) {
let temp:T = data[i]
data[i] = data[j]
data[j] = temp
}
You can simply do:
swap(&data[i], &data[j])
If you want to write a generic function it will be this:
func exchange<T>(inout data: [T], i: Int, j: Int) {
swap(&data[i], &data[j])
}
var array = ["a", "b", "c", "d"]
exchange(&array, 0, 2)
array // ["c", "b", "a", "d"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With