代码之家  ›  专栏  ›  技术社区  ›  Richard Topchii

swift数组:带有indexpath的下标-无法更改

  •  2
  • Richard Topchii  · 技术社区  · 6 年前

    我想在数组数组中添加一个扩展来检索 Element 索引路径 尺寸2:

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

    我有个错误 无法通过下标赋值下标为get only 在实现以下扩展时:

    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
        }
      }
    }
    

    造成这种错误的原因是什么?如何将突变选项添加到 下标 ?

    1 回复  |  直到 6 年前
        1
  •  7
  •   Martin R    6 年前

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

    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
            }
        }
    }