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

Slava Pestov spestov at apple.com
Fri Dec 18 15:30:08 CST 2015


> On Dec 16, 2015, at 6:17 AM, Marco Masser via swift-evolution <swift-evolution at swift.org> wrote:
> 
> In Objective-C, I liked that fast enumeration over an NSArray that was nil and one that was empty could be handled with the exact same code:
> 
> NSArray *strings = nil;
> for (NSString *string in strings) {
>> }

One thing we've discussed is adding attributes to import nil values of NSArray and such as empty arrays in Swift, rather than optionals of arrays. Would this solve your problem? Where are these optional arrays coming from in the first place, is it imported Cocoa APIs?

> Handling a sequence that is empty or one that is nil is often the same, at least in my experience. Granted, this points to an API that could be improved to return empty sequences instead of nil in many cases, but that is not always in one’s control. For example in AppKit, NSView’s subviews property is declared as [NSView], while NSWindow’s childWindows property is [NSWindow]?, an optional Array.

Yeah, exactly. We want to be able to fix this.

> Also, this is not a proposal to make the Optional type conform to SequenceType as was also discussed previously. If that were to be implemented, my proposal would be pointless, but you’d lose the distinction between iterating over an Optional<SequenceType> and a SequenceType. Therefore, I’d prefer a specialized syntax to make a clear distinction between iterating over a SequenceType and an Optional<SequenceType>.

Actually it depends on how the conformance was defined. If Optional<T> was a sequence iff T is a sequence, then yes it supersedes your proposal. Another way to imagine Optional<T> as a sequence is to make it a zero- or one-element sequence, depending on if it is None or Some, respectively. I'm not sure which, if either, is more useful.

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

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


More information about the swift-evolution mailing list