[swift-evolution] Strings in Swift 4

Nate Cook natecook at gmail.com
Mon Jan 30 11:31:11 CST 2017


> On Jan 30, 2017, at 8:51 AM, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> Am 23.01.2017 um 02:14 schrieb James Froggatt via swift-evolution <swift-evolution at swift.org>:
>> 
>> Could we add subscript labels to the list of options? While keeping the range syntax is appealing, I'm concerned it may cause confusion if the operators are used out of context.
> 
> Good point!
> 
>> The wording is up for debate, but something like this should be a fair alternative:
>> items[from: i]
>> items[upTo: i]
> 
> For me that's at least as readable as the range syntax.
> 
>> 
>> Sorry if this has been covered elsewhere (can't find the answer in this thread), but my first questions on discovering these operators (my source of confusion) would be what happens if I try the following:
>> let partialRange = 0..< //is this an infinite range?
>> let x = items[partialRange] //shouldn't this cause an out of bounds error?
> 
> Good point! Probably this shouldn't be allowed, making the literal range syntax with open ends tied into the subscript which is a bit confusing indeed.

`partialRange` here is an incomplete range, not an infinite one. When you use an incomplete range to subscript a collection, the collection "completes" it by filling in the start or end index as required. You can see more about the details of incomplete ranges in this proposal: https://github.com/apple/swift-evolution/blob/master/proposals/0132-sequence-end-ops.md

One other aspect of incomplete ranges that I haven't seen discussed (though I may have missed it) is how they work inpattern matching. It would be nice to use incomplete ranges in switch statements, so that instead of:

    switch x {
    case let y where y < 0: print("< 0")
    case 0...10: print("0-10")
    case let y where y > 10: print("> 10")
    default: print("wat")
    }

we could write:

    switch x {
    case ..<0: print("< 0")
    case 0...10: print("0-10")
    case 10...: print("> 10")
    default: print("wat")
    }

To me, that implies that we'll want a postfix ... operator to exist, though I agree it's not clear what it should do in a subscript. Are there contexts in which we would want i... and i..< to do different things?

Nate



More information about the swift-evolution mailing list