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

Dave Abrahams dabrahams at apple.com
Wed Dec 16 13:02:42 CST 2015


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

FWIW, the above only works when "array" is an array or set.  In a generic context you might not even know how to construct an empty one.

a?.forEach { object in ... }

is the generic version I think.

> 
> -Chris
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

-Dave



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


More information about the swift-evolution mailing list