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

Marco Masser lists at duckcode.com
Wed Dec 16 08:17:37 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) {
    …
}

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 '?'?
    …
}

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

for object in array ?? [] {
    …
}

… or what I would consider the proper way:

if let array = array {
    for object in array {
        …
    }
}

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.


Although I’m not sure this justifies adding a special syntax to Swift, I thought I post this here to see what others think.
I’m proposing a feature that allows iterating over an Optional<SequenceType> if it is not nil, while doing nothing when it is nil. I think that this should be separate from the normal for loop (my first Swift code sample above with the compiler error), but a specialized syntax instead, like the following:

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

With this specialized syntax, you’d be able to see at a glance whether you’re dealing with an Optional or not. The first Swift code sample in this message would still be a compiler error because it uses “for … in”, but Xcode could show a fix-it that points to the “for … in?” syntax.
This syntax would not interfere with other proposals discussed on this list, like adding a mandatory ? to identifiers to Optionals (although this does not imply endorsement on my part).

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

Cheers,

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


More information about the swift-evolution mailing list