【问题标题】:Swift Array: subscript with IndexPath - unable to mutateSwift Array:带有 IndexPath 的下标 - 无法变异
【发布时间】:2018-11-28 11:01:34
【问题描述】:

我想为数组数组添加一个扩展,以检索大小为 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
    }
  }
}

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

【问题讨论】:

    标签: ios arrays swift collections subscript


    【解决方案1】:

    为了改变嵌套数组,您必须这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2020-01-19
      • 2019-03-11
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多