[英]Swift - Cannot subscript a value of type '[Array<String>]' with an index of type 'IndexPath'
[英]Swift Array: subscript with IndexPath - unable to mutate
我想为数组数组添加一个扩展来检索IndexPath大小为2的Element
:
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
}
}
}
出现这种错误的原因是什么? 如何在下标中添加变异选项?
为了改变嵌套数组,你必须要求它
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.