Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exchange array elements in Swift

Tags:

swift

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
}
like image 800
Zhijie Liu Avatar asked Mar 15 '26 12:03

Zhijie Liu


1 Answers

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"]
like image 157
Essan Parto Avatar answered Mar 18 '26 07:03

Essan Parto