我在Array上定义了一个扩展来覆盖Slice创建:
struct S<T> {
private var array: [T] = []
private var first = 0
private var len = 0
init(_ array: [T], _ range: Range<Int>? = nil) {
self.array = array
if let range = range {
self.first = range.startIndex
self.len = range.endIndex
} else {
self.first = 0
self.len = array.count
}
}
}
extension Array {
subscript(subRange: Range<Int>) -> S<T> {
return S<T>(self, subRange)
}
}
let a = [4, 3, 2, 1, 0, -1][2..<4 as Range<Int>]
但是,我在定义a时遇到错误:&#34;范围不能转换为Int&#34; (没有演员,错误是&#34; HalfOpenInterval ......&#34;)。我做错了什么?
答案 0 :(得分:1)
因为Array
已经具有子片段功能:
typealias SubSlice = Slice<T>
subscript (subRange: Range<Int>) -> Slice<T>
因此,为了实现您的实现,您必须明确指定返回类型:
let a = [4, 3, 2, 1, 0, -1][2..<4] as S<Int>