[swift-evolution] Range and ClosedRange
David Sweeris
davesweeris at mac.com
Thu Jan 12 16:55:30 CST 2017
> On Jan 12, 2017, at 15:44, Adriano Ferreira via swift-evolution <swift-evolution at swift.org> wrote:
>
> BTW, I agree with you, having the range type split is somewhat confusing, specially for those new to the language.
Do you mean that you think having two types is confusing, or that the way we currently split them is confusing?
If it's the former, then I disagree... IIRC, open vs closed ranges is covered in high school math, and IMHO it's not too hard to see the usefulness of both "0..<5" and "1...5".
If it's the latter, I think it's only confusing because, well, partly because we only implement half the kinds of ranges ("lower" is always closed, but that's another thread), but mostly because we don't have generic protocols yet. If we could write
protocol Range<T> where T : WhateverTheCurrentConstraintsAre {
var lower: T {get}
var upper: T {get}
}
Then we could define the concrete types as
struct CCRange<T>: Range<T> {...}
struct CORange<T>: Range<T> {...}
struct OCRange<T>: Range<T> {...}
struct OORange<T>: Range<T> {...}
(Or spell it out, "ClosedClosedRange", if you don't like the abbreviations.) Then in code, since `Range` doesn't have any "Self or associated type requirements", you can make just make it the type of a variable. In fact, if I'm not mistaken, the "..<" and "..." operators could even return a `Range` instead of the relevant concrete type
var x = 0..<5 // "..<" returns `CORange as Range`
x = 0...4 // "..." returns `CCRange as Range`, which is fine because x's type is `Range`, not `HalfOpenRange` (or whatever it's called now)
We'd get full polymorphism between all the types of range without losing the value semantics we want, and the current method of overloading functions is still available if you need the speed of static dispatch.
- Dave Sweeris
More information about the swift-evolution
mailing list