arrays - 快速交换数组对象

标签 arrays uitableview swift

我无法在单元格重新排序时交换字符串数组:

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/

相关文章:

ios - 使用 Swift 解析 Json

Swift - 完成后重置/重启 SpeechSynthesizer

javascript - 为什么数组解构在这种情况下不起作用?

javascript 迭代嵌套对象数组中的对象并按 ids 过滤并返回更新后的相同原始数据集

ios - 最佳方法 : Displaying a "nothing here, yet" screen instead of empty tableView cells

ios - 自调整 TableView 单元格不起作用

iphone - UITableViewCell 中的 UIActivityIndi​​catorView 不会停止旋转

swift - 有没有办法将快速方法注释为需要调用其父类(super class)的实现

java - 如何在java中迭代字符串数组的一列

Java,基本数组错误