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?
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:
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With