Arrays in Swift is value types. That's means data
that's copied when passed into your exchange
method, but you were trying to modify the copy to affect the Ori Ginal version. Instead should do one of the things:
1. Define
data
As an
inout
Parameter
func exchange<T>(inout data:[T], i:Int, j:Int)
Then when calling it has to add a 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= data newdata[i ] = Data[] Newdata[j = Data[i ] return Newdata}
I recommend this to the In-out parameter because in-out parameters create more complicated state. You have both variables pointing to and potentially manipulating the same piece of memory. What if the decided to does it work on exchange
a separate thread? There is also a reason the Apple decided to make arrays value types, using In-out subverts. Finally, returning a copy is much closer tofunctional programming which are a promising direction that Swift can move. The less state we had in our apps, the fewer bugs we'll create (in general).
Http://stackoverflow.com/questions/24784252/swift-generic-array-not-identical-error
Swift Generic Array ' not identical ' error