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


You can simply do:

swap(&data[i], &data[j])

      



If you want to write a generic function, it would be like 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"]

      

+8


source


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







All Articles