![](/img/trans.png)
[英]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.