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

Marco Masser lists at duckcode.com
Sun Dec 20 11:21:44 CST 2015


>> 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?

Yes, mostly. But I still can imagine cases where it makes sense to have an API that returns an Optional Array but the caller doesn’t care about it being nil vs. it being empty – not that I have a practical example.

Importing an Objective-C API’s NSArray nil value as an empty array in Swift sounds nice!


>> 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.

I have to admit that I didn’t closely follow the discussion about Optionals being sequences of zero or one element and therefore don’t know all of the arguments for and against that – just enough that it would supersede my proposal.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151220/e2984d97/attachment.html>


More information about the swift-evolution mailing list