Swift Generic Array 'not identical' error
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 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。