更新:从 Swift 3.2/4 (Xcode 9) 开始,您必须使用 swapAt() 方法
集合
scatola.swapAt(fromIndexPath.row, toIndexPath.row)
因为将数组作为两个不同的
inout 同一函数的参数不再合法,
比较SE-0173 Add MutableCollection.swapAt(_:_:))。
更新:我用 Xcode 6.4 再次测试了代码,发现问题
不再发生。它按预期编译和运行。
(旧答案:) 我假设 scatola 是视图控制器中的存储属性:
var scatola : [Int] = []
您的问题似乎与https://devforums.apple.com/thread/240425 中讨论的问题有关。它已经可以通过以下方式复制:
class MyClass {
var array = [1, 2, 3]
func foo() {
swap(&array[0], &array[1])
}
}
编译器输出:
错误:inout writeback to computed property 'array' 发生在多个要调用的参数中,引入了无效的别名
交换(&数组[0],&数组[1])
^~~~~~~~
注意:这里发生并发写回
交换(&数组[0],&数组[1])
^~~~~~~~
我还没有掌握
讨论的内容完全(这里为时已晚:),但有一个提议
“解决方法”,即将属性标记为最终的(这样你就不能覆盖它
在子类中):
final var scatola : [Int] = []
我发现的另一种解决方法是获取底层数组存储的指针:
scatola.withUnsafeMutableBufferPointer { (inout ptr:UnsafeMutableBufferPointer<Int>) -> Void in
swap(&ptr[fromIndexPath.row], &ptr[toIndexPath.row])
}
当然,万无一失的解决方案就是
let tmp = scatola[fromIndexPath.row]
scatola[fromIndexPath.row] = scatola[toIndexPath.row]
scatola[toIndexPath.row] = tmp