-
Notifications
You must be signed in to change notification settings - Fork 448
Add random-access methods to SlidingWindows #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add random-access methods to SlidingWindows #42
Conversation
Do you think it's worth considering a better implementation of |
That's always worth considering, but I don't think there is any! If we want Of course we could give Having said all that, it's totally possible to write a struct CollectionOfTwo<Element> {
let first, second: Element
}
extension CollectionOfTwo: ValidIndexCollection {
enum ValidIndex: Comparable {
case first, second
}
func element(at index: ValidIndex) -> Element {
index == .first ? first : second
}
var firstValidIndex: ValidIndex? { .first }
var lastValidIndex: ValidIndex? { .second }
func validIndex(after index: ValidIndex) -> ValidIndex {
.second
}
} where |
} | ||
|
||
private func offsetForward(_ i: Index, by distance: Int) -> Index { | ||
offsetForward(i, by: distance, limitedBy: endIndex)! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of force unwrapping here (and offsetBackward
) I would add an error message describing why the offset was not valid. We did something similar here
// | ||
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x] | ||
// |> > >|>| or |> > >| | ||
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👏 This is excellent and a massive help when reviewing this code
Thanks, @timvermeulen! 👏 |
index(_:offsetBy:)
,index(_:offsetBy:limitedBy:)
, anddistance(from:to:)
forSlidingWindows
.The
base.endIndex..<base.endIndex
representation ofendIndex
made this a bit tricky, because neither of the bounds is a logical successor of the index before it. TheoffsetForward
/offsetBackward
dance alleviates this somewhat by ensuring that the limit is always on the correct side ofi
and never equal to it, removing some of the edge cases.Checklist