我无法在单元格重新排序时交换一个字符串数组
var scatola : [String] = []
override func tableView(tableView: UITableView,moveRowAtIndexPath fromIndexPath: NSIndexPath,toIndexPath: NSIndexPath) {
swap(&scatola[fromIndexPath.row],&scatola[toIndexPath.row])
}
此代码抛出:inout writeback到计算属性“scatola”发生在多个参数中调用,引入无效的别名
什么是正确的方法呢?
谢谢
更新:我用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])
}
}
编译器输出:
error: inout writeback to computed property 'array' occurs in multiple arguments to call,introducing invalid aliasing
swap(&array[0],&array[1])
^~~~~~~~
note: concurrent writeback occurred here
swap(&array[0],&array[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