Swift Generic Array Error Not Identical

I'm just looking at some Swift that are obviously already deprecated by Beta3 ...

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

Playgrounds tell me:

Error: @lvalue $ T8 does not match T.

How do I change it to make it work?

+4
source share
1 answer

Arrays in Swift are value types. This means that it is datacopied when passing to your method exchange, but you are trying to modify the copy to affect the original version. Instead, you should do one of two things:

1. Define dataas a parameter inout:

func exchange<T>(inout data:[T], i:Int, j:Int)

Then, calling it, you must add &before the call:

var myArray = ["first", "second"]
exchange(&myArray, 0, 1)

2. ()

func exchange<T>(data:[T], i:Int, j:Int) -> [T]
{
    var newData = data
    newData[i] = data[j]
    newData[j] = data[i]
    return newData
}

in-out, in-out . , . , exchange ? , Apple , in-out subverts. , , , Swift. , ( ).

+11

Source: https://habr.com/ru/post/1548656/


All Articles