[swift-users] Compact iteration of optional collection?

Quinn "The Eskimo!" eskimo1 at apple.com
Fri Jul 29 02:53:10 CDT 2016


On 28 Jul 2016, at 22:55, Rick Mann via swift-users <swift-users at swift.org> wrote:

> I often call methods that return an optional collection.

Why do these methods return an optional collection rather an empty collection? Back in the day Cocoa code used to work that way because constructing empty collections was expensive.  These days I avoid optionality unless that optionality is signalling something relevant.  So I never write code like this:

    if let container = someOptionalContainer {
        for item in container {
            [do stuff with item]
        }
    }

it’s always this:

    for item in container {
        [do stuff with item]
    }

or this:

    if let container = someOptionalContainer {
        for item in container {
            [do stuff with item]
        }
    } else {
        [do other stuff]
    }

Share and Enjoy
--
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware




More information about the swift-users mailing list