ios - swift 数组 : subscript with IndexPath - unable to mutate

标签 ios arrays swift collections subscript

我想为数组的数组添加一个扩展,以检索具有大小为 2 的 IndexPathElement:

let array: [[String]] =  ....
let indexPath = IndexPath(indexes: [0, 0])
let string = array[indexPath]

我在实现以下扩展时遇到错误无法通过下标分配下标是只获取:

extension Array where Element : Collection, Element.Index == Int {
  subscript(indexPath: IndexPath) -> Element.Iterator.Element {
    get {
      return self[indexPath.section][indexPath.item]
    }
    set {
      self[indexPath.section][indexPath.item] = newValue
    }
  }
}

出现这种错误的原因是什么?如何向下标添加突变选项?

最佳答案

为了改变嵌套数组你必须要求

Element : MutableCollection

代替 Element : Collection

你还可以定义两个扩展名:一个只读的下标用于只读 集合,以及可变集合的读写下标:

extension Collection where Index == Int, Element : Collection, Element.Index == Int {
    subscript(indexPath: IndexPath) -> Element.Iterator.Element {
        return self[indexPath[0]][indexPath[1]]
    }
}

extension MutableCollection where Index == Int, Element : MutableCollection, Element.Index == Int {
    subscript(indexPath: IndexPath) -> Element.Iterator.Element {
        get {
            return self[indexPath[0]][indexPath[1]]
        }
        set {
            self[indexPath[0]][indexPath[1]] = newValue
        }
    }
}

关于ios - swift 数组 : subscript with IndexPath - unable to mutate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929115/

相关文章:

ios - 使用 instantiateViewController 时防止内存泄漏

ios - 使用 Core Animation 的循环、可逆动画

c - 通用字符缓冲区用作具有灵活数组成员的结构数组

ios - 是否可以在 iOS 应用程序中本地使用 mongoDB?

C 将字符命令行参数转换为整数数组

java - 为什么这个类被认为是可变的?

swift - 更改 CorePlot 中轴上数字的大小

iphone - 提取NSCFConstantString的第一项

iphone - 如何从嵌套的 UIViewController 中获取正确的 UIInterfaceOrientation

ios tableview 表中的最后一个单元格缺少分隔符 swift