[swift-evolution] Proposal: Add syntactic sugar for iterating over an Optional<SequenceType>

Paul Cantrell cantrell at pobox.com
Fri Dec 18 14:56:23 CST 2015


> On Dec 17, 2015, at 4:08 AM, Jeremy Pereira <jeremy.j.pereira at googlemail.com> wrote:
> 
> 
>> On 16 Dec 2015, at 19:52, Paul Cantrell via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> I do this a lot:
>> 
>>    for object in array ?? [] {
>> 
>> …and it does impair readability a bit at times.
> 
> Does it? It seems fairly understandable to me even though I have never seen it before.

Sure, in that example it’s quite simple. It’s not the “?? []” syntax itself, which is perfectly clear; it’s having that dangling off the end of some longer expression. In real-world context, it does become additional noise.

> I think there is a good reason for keeping this construct a bit “clunky”. Generally APIs give you a nil array for one of two reasons:
> 
> - there was some sort of error in retrieving the elements
> - there were no qualifying elements found.

You’re forgetting the third case, the most common one: things not populated / initialized yet. In that case, we often just want to leave a UI blank, for example, and doing nothing is the right behavior.

Doing nothing is the right behavior in a lot of cases, and since Swift provides optional sugar for “do nothing if nil” in other cases:

    foo?.bar = baz
    if let foo = bar { }

…it makes sense to provide it in for loops too.

True, “do nothing” is not the right behavior in all cases. Thus the `for…in` / `for … in?` distinction.

> In the second case, the API is wrong.

Then a lot of APIs are wrong! NSURLComponents, for example:

        for item in urlComponents.queryItems ?? []
            { queryDict[item.name] = item.value }

But then I don’t think NSURLComponents is making a mistake: it distinguishes “no query string” from “empty query string”, but for the purposes of the loop here, there upshot in both cases is “no query items.”

True, ?? [] is minor noise — but given the clarity and low impact on existing code of a `for … in?` counterpart to `for … in`, it’s worth at least considering that option.

Cheers,

Paul



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/aa0d196e/attachment.html>


More information about the swift-evolution mailing list