[swift-evolution] Feature proposal: Range operator with step
Brent Royal-Gordon
brent at architechies.com
Wed Mar 30 01:17:02 CDT 2016
> We don't make String a sequence for similar reasons (though perhaps, by analogy to String, there could be `seconds`/`days`/`solarMonths`/`lunarMonths`/etc. views that are Strideable).
Well, you managed to nerd snipe me pretty hard with this suggestion.
First design: https://gist.github.com/brentdax/e73402b36f71feb7d8a8190fa1e1d096
let date = NSDate()
let now = date.unitView(.Day)
let tomorrow = now + 1
let yesterday = now - 1
for view in yesterday.stride(through: tomorrow, by: 1) {
print(view.date)
}
This seems to be really clunky. The linkage between date and unit/calendar is poorly motivated and arbitrary. The preconditions in `distanceTo(_:)` are scary, and converting back to a date is annoying and painful.
Second design: https://gist.github.com/brentdax/4272a3e01ed7037d2c5d6ba413ecf2a9
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let tomorrow = now + calendar.interval(1, .Day)
let yesterday = now - calendar.interval(1, .Day)
for date in yesterday.stride(through: tomorrow, by: calendar.interval(1, .Day)) {
print(date)
}
This could use a lot of design improvements—NSCalendar.Interval could carry an NSDateComponents, which would allow arithmetic with intervals, and the syntax could be improved with various conveniences to the point where you could write things like `days(1, in: calendar)` or just `days(1)`—but I think this is enough to get a sense of the direction.
Calendar intervals make more sense as a concept, and the implementation has fewer crazy preconditions—though there are still a couple—but `distanceTo` is unimplementable and there are various other ridiculous limitations. (One of them comes from Strideable indirectly requiring IntegerLiteralConvertible when it really just needs some way to construct a zero value.) Basically, you can make this work for the basics but it's not actually a good semantic match for Strideable.
The safety of both of these designs could benefit from dependent types, but of course we don't have those.
The general sense I have is that this badly needs some kind of context object, but Strideable is simply not designed that way.
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list