是否可以扩展数组以使用[[_ x:Int]]形式的下标,这实际上意味着[x-1]?例如,如果您访问array [[n]],则将访问数组的第n个元素。
答案 0 :(得分:0)
好吧,我将为subscript
创建Array
,并使用不同的参数标签
extension Array {
subscript(nth nthIndex: Int) -> Element {
get {
return self[nthIndex - 1]
}
set(newValue) {
self[nthIndex - 1] = newValue
}
}
}
用法:
let array = ["first", "second", "third"]
print(array[nth: 1])
first
或者,您可以使用这种黑客解决方案,该解决方案将Int
数组作为参数
extension Array {
subscript(index: [Int]) -> Element {
get {
guard index.count == 1, let index = index.first else { fatalError("Fatal error: You have to pass exactly one index") }
return self[index - 1]
}
set(newValue) {
guard index.count == 1, let index = index.first else { fatalError("Fatal error: You have to pass exactly one index") }
self[index - 1] = newValue
}
}
}
用法:
let array = ["first", "second", "third"]
print(array[[1]])
first