[swift-evolution] Strings in Swift 4

Dave Abrahams dabrahams at apple.com
Thu Feb 2 13:36:01 CST 2017


on Thu Feb 02 2017, Jonathan Hull <swift-evolution at swift.org> wrote:

> I really like the IncompleteRange/RangeExpression idea!
>
> I don’t think that IncompleteRange/RangeExpression should, by themselves, conform to Sequence. It
> seems like necessary information is missing there.  Instead, there needs to be a conditional
> conformance to Sequence based on another protocol that provides the natural bounds for the Bound
> type.
>
> For example, what if we have another protocol:
>
> 	protocol FiniteComparable : Comparable { //Any finite set which is comparable will have a
> lowest value and a highest value...
> 		static var lowestValue:Self {get}
> 		static var highestValue:Self {get}
> 	}
>
> Something like UInt would have a lowestValue of 0 and highestValue of (UInt.max -1).  Then you could
> conditionally conform a RangeExpression where the Bounds are FiniteComparable to Sequence.
>
> Now the behavior is consistent.  In the case of ‘array[0…]’ the array is providing the missing upper
> bound.  In the case of ‘for n in 0…’ the conformance to FiniteComparable is providing the bound (and
> it doesn’t trap, because it is enumerating all values IN that type above the lower bound).
>
> 	for n in UInt8(0)… {/* Will get called for every possible value of UInt8 */}
>
> I agree that trapping when an infinite sequence of integers goes past the max value is the only
> reasonable thing to do in that situation... but since we get to define the bounds (and we have
> defined them in other cases to be the largest usable value), why not define them the same way here
> (i.e. not infinite).  In this case, I don’t see the added value in making the sequence infinite
> instead of just bounded by what the type can represent.  The only thing it seems it adds is the
> trapping behavior.  With the natural bound, you can use things like filter on partially defined
> ranges (which would trap if they are defined as infinite):
>
> 	let odd:[UInt8] = (0…).filter({$0 & 1 != 0}) //returns an array of all the odd UInt8

Why store them?  This is all the odd integers, and it traps only when
you exceed the machine's ability to express the values.

    let odd = (0...).lazy.filter({$0 & 1 != 0}) 

If you really want a range that is limited to the Int8s, just use
Int8.max as your upper bound on a closed range.  That's exactly what
closed ranges and .max static properties are for. It's much better to
explicitly say, “I expect this range to stop” than for us to potentially
hide bugs by silently bounding the range at a value that depends on type
context.

-- 
-Dave



More information about the swift-evolution mailing list