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

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu Dec 17 04:08:04 CST 2015

> On 16 Dec 2015, at 19:52, Paul Cantrell via swift-evolution <swift-evolution at swift.org> wrote:
> This is such a minor thing, but I’ve often wished for “for … in? …” and I like that syntax.
> 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.

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.

In the first case, I think it would be more appropriate to handle the error separately to trying to iterate the results (e.g. guard). In the second case, the API is wrong. If there were no qualifying elements, the API should have returned an empty array rather than nil. The very slight clunkiness of the above serves to remind you that you need to change the API that returns the array (assuming you control it).

More information about the swift-evolution mailing list