我无法在单元格重新排序时交换字符串数组:
var scatola : [String] = []
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
swap(&scatola[fromIndexPath.row], &scatola[toIndexPath.row])
}
这段代码抛出:
inout writeback to computed property 'scatola' occurs in multiple arguments to call, introducing invalid aliasing
正确的做法是什么?
最佳答案
更新:自 Swift 3.2/4 (Xcode 9) 起,您必须使用 swapAt()
方法
集合
scatola.swapAt(fromIndexPath.row, toIndexPath.row)
因为将数组传递为两个不同的
inout
相同函数的参数不再合法,
比较 SE-0173 Add MutableCollection.swapAt(_:_:)
).
更新我用Xcode 6.4再次测试了代码,问题 不再发生。它按预期编译和运行。
(旧答案:) 我假设 scatola
是 View Controller 中的存储属性:
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]) ^~~~~~~~
I haven't yet grasped the contents of the discussion completely (too late here :), but there is one proposed "workaround", namely to mark the property as final (so that you cannot override it in a subclass):
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
关于arrays - 快速交换数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307410/