我想为数组的数组添加一个扩展,以检索具有大小为 2 的 IndexPath 的 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
}
}
}
出现这种错误的原因是什么?如何向下标添加突变选项?
最佳答案
为了改变嵌套数组你必须要求
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/