Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Generic Array 'not identical' error

I'm just going through some Swift tuts that are obviously already outdated as of Beta3 ...

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

Playgrounds tells me:

Error: @lvalue $T8 is not identical to T.

How do I change it to make it work?

like image 391
BadmintonCat Avatar asked Dec 20 '22 13:12

BadmintonCat


1 Answers

Arrays in Swift are value types. That means that data is copied when passed into your exchange method, but you are trying to modify the copy to affect the original version. Instead you should do one of two things:

1. Define data as an inout parameter:

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

Then when calling it you have to add an & before the call:

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

2. Return a copy of the Array (recommended)

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

I recommend this way over the in-out parameter because in-out parameters create more complicated state. You have two variables pointing to and potentially manipulating the same piece of memory. What if exchange decided to do its work on a separate thread? There is also a reason that Apple decided to make arrays value types, using in-out subverts that. Finally, returning a copy is much closer to Functional Programming which is a promising direction that Swift can move. The less state we have in our apps, the fewer bugs we will create (in general).

like image 69
drewag Avatar answered Jan 03 '23 01:01

drewag