3

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
}
1

2 Answers 2

8

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"]
Sign up to request clarification or add additional context in comments.

Comments

1

data needs to be an inout parameter:

func exchange<T>(inout data: [T], i:Int, j:Int) {
    let temp:T = data[i]
    data[i] = data[j]
    data[j] = temp
}

You'd call it like:

var array = [1,2,3]
exchange(&array, 0, 2)

See in-out parameters in the swift programming guide.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.