Reputation: 77
I'm defining an extension on Array to override Slice creation:
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>]
However, I'm getting an error on defining a: "Range is not convertible to Int" (without the cast the error is "HalfOpenInterval ..."). What am I doing wrong?
Upvotes: 2
Views: 1086
Reputation: 51911
Because Array
already have subslice functionality:
typealias SubSlice = Slice<T>
subscript (subRange: Range<Int>) -> Slice<T>
So, in order to your implementation work, you have to explicitly specify the return type:
let a = [4, 3, 2, 1, 0, -1][2..<4] as S<Int>
Upvotes: 1