Swift数组:带有IndexPath的下标-无法突变

时间:2018-06-19 12:59:35

标签: ios arrays swift collections subscript

我想向数组数组添加扩展,以检索 IndexPath 大小为2的Element

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

这种错误的原因是什么?如何为下标添加一个突变选项?

1 个答案:

答案 0 :(得分:7)

要变异嵌套数组,您必须要求

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