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

Chris Lattner clattner at apple.com
Wed Dec 16 12:51:20 CST 2015

On Dec 16, 2015, at 6:17 AM, Marco Masser via swift-evolution <swift-evolution at swift.org> wrote:
> 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.

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

More information about the swift-evolution mailing list