Proposal: Add syntactic sugar for iterating over an Optional<SequenceType>

In Swift, an Optional<SequenceType> can’t be used this way:

let array: [AnyObject]? = nil
for object in array { // Compiler error: Value of optional type '[AnyObject]?' not unwrapped; did you mean to use '!' or '?'?
    …
}

This topic has come up in internal discussions several times. We’ve discussed adding new features to for/in loop to handle it, having something like “in?” as you suggest:

let array: [AnyObject]? = nil
for object in? array { // Note the “in?”
    …
}

etc. However, the discussion kept coming back to the fact that we have a pretty trivial way to express this already:

I know this is a very minor thing and it can be worked around easily by code like this:

for object in array ?? {
    …
}

Thus this isn’t really solving a big problem, and making the language more complex isn’t worth it.

-Chris

···

On Dec 16, 2015, at 6:17 AM, Marco Masser via swift-evolution <swift-evolution@swift.org> wrote: