gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:59:44 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com