码迷,mamicode.com
首页 > 编程语言 > 详细

Swift Generic Array 'not identical' error

时间:2014-09-02 21:07:15      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:http   os   io   ar   for   cti   sp   amp   on   

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

Swift Generic Array 'not identical' error

标签:http   os   io   ar   for   cti   sp   amp   on   

原文地址:http://www.cnblogs.com/jinks/p/3952129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!