数组 – Swift交换数组对象
发布时间:2020-12-14 05:19:16 所属栏目:百科 来源:网络整理
导读:我无法在单元格重新排序时交换一个字符串数组 var scatola : [String] = []override func tableView(tableView: UITableView,moveRowAtIndexPath fromIndexPath: NSIndexPath,toIndexPath: NSIndexPath) { swap(scatola[fromIndexPath.row],scatola[toIndexP
我无法在单元格重新排序时交换一个字符串数组
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |