I noticed no subscript of Array
for stride
.
var x = Array(0..<10)
x[stride(from: 1, through: 8, by: 2)] = [-1, -2, -3]
// should be [0, -1, 2, -2, 4, -3, 6, 7, 8, 9]
gives error messages:
error: repl.swift:2:2: error: cannot subscript a value of type '[Int]' with an index of type 'StrideThrough<Int>'
x[stride(from: 1, through: 8, by: 2)] = [-1, -2, -3]
^
repl.swift:2:2: note: overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>), (Range<Self.Index>), ((UnboundedRange_) -> ())
x[stride(from: 1, through: 8, by: 2)] = [-1, -2, -3]
^
First, I made minor modification to Alexandre's implementation as the following:
precedencegroup StrideStopPrecedence {
higherThan: RangeFormationPrecedence
}
precedencegroup StrideFormationPrecedence {
higherThan: StrideStopPrecedence
lowerThan: AdditionPrecedence
}
infix operator ..+ : StrideFormationPrecedence
infix operator ..! : StrideStopPrecedence
infix operator ... : StrideStopPrecedence
func ..+ <T: Strideable>(start: T, step: T.Stride) -> Stride<T> {
return stride(from: start, by: step)
}
Then, I added an extension of Array
to subscript Array
with stride
:
extension Array {
subscript (stride: Stride<Int>) -> Array<Element> {
get {
let stride = stride.stop(before: self.count)
return stride.map { self[$0] }
}
set (newValues) {
let stride = stride.stop(before: self.count)
zip(stride, newValues).forEach { self[$0] = $1 }
}
}
subscript (stride: StrideTo<Int>) -> Array<Element> {
get {
return stride.map { self[$0] }
}
set (newValues) {
zip(stride, newValues).forEach { self[$0] = $1 }
}
}
subscript (stride: StrideThrough<Int>) -> Array<Element> {
get {
return stride.map { self[$0] }
}
set (newValues) {
zip(stride, newValues).forEach { self[$0] = $1 }
}
}
}
For example,
var x = Array(0..<10)
x[stride(from: 1, by: 2)]
x[1..+2]
// [1, 3, 5, 7, 9]
x[stride(from: 1, to: 8, by: 2)]
x[1..+2..!8]
// [1, 3, 5, 7]
x[stride(from: 1, through: 8, by: 2)]
x[1..+2...8]
// [1, 3, 5, 7]
x = Array(0..<10)
x[1..+2] = [-1, -2, -3]
// [0, -1, 2, -2, 4, -3, 6, 7, 8, 9]
x[1..+2] = [-1, -2, -3, -4]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, 9]
x[1..+2] = [-1, -2, -3, -4, -5]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, -5]
x = Array(0..<10)
x[1..+2..!8] = [-1, -2, -3]
// [0, -1, 2, -2, 4, -3, 6, 7, 8, 9]
x[1..+2..!8] = [-1, -2, -3, -4]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, 9]
x[1..+2..!8] = [-1, -2, -3, -4, -5]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, 9]
x = Array(0..<10)
x[1..+2...8] = [-1, -2, -3]
// [0, -1, 2, -2, 4, -3, 6, 7, 8, 9]
x[1..+2...8] = [-1, -2, -3, -4]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, 9]
x[1..+2...8] = [-1, -2, -3, -4, -5]
// [0, -1, 2, -2, 4, -3, 6, -4, 8, 9]
Is there another implementation for the subscript?