Swift Generic Array 'not identical' error

Arrays in Swift are value types. That means that data is copied when passed into your exchangemethod, 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 toFunctional 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).

http://stackoverflow.com/questions/24784252/swift-generic-array-not-identical-error

posted @ 2014-09-02 19:15  Jinks  阅读(274)  评论(0编辑  收藏  举报