rethrows in Swift

Rethrows saves us a lot of duplicate code. Look at my naive approach to write an iterator in Swift 1 from last year which I later extended for throwing with Swift 2:

extension Array {
    func each(@noescape iterator: (Element) -> Void) {
        for element in self {
            iterator(element)
        }
    }
    
    func each(@noescape iterator: (Element) throws -> Void) throws {
        for element in self {
            try iterator(element)
        }
    }
}

This can be written as a single method with Swift 2 as I later found out:

extension Array {
    func each(@noescape iterator: (Element) throws -> Void) rethrows {
        for element in self {
            try iterator(element)
        }
    }
}

The rethrows keyword makes the method a throwing one depending on the closure you pass in. Only if the closure throws each will throw, too. The compiler will know what happens – just like generic functions are write-once, use-many-times.

Of course I later found out that Swift 2 came with forEach already bundled in. So there’s no use in this anymore except for this very illustrative blog post to remember that throws/rethrows is different from throws/throws.

Always Write Functions to Cope with all Possible Parameter Values

Matt Galagher is back writing at Cocoa with Love. His goal is maintainability, which is the greatest of all, I think. It’s easy to copy code samples together to create an app, bur it’s hard to create a product you can keep alive and make better over years. In that vein, his first article, “Partial functions in Swift, Part 1: Avoidance”, includes a lot of details why partial functions will hurt you. This is a great topic. Read his post for the basic set theory involved.

Continue reading …

How I Solve the Unexpected Error Handling User Experience Problem

Teaser image

For the upcoming Word Counter upgrade, I developed a new feature module in isolation. The outcome is very interesting, as I am including it as a Swift module, that is as a real framework, into the existing app. I need some more time to write about the resulting architecture, but I found the module boundary to be really helpful. Today, though, I want to share my ErrorHandling code.

Continue reading …

Success and Error Callbacks in Objective-C: a Refactoring

I’m refactoring code of Calendar Paste 2 some more. Since I like what I learned using Swift so much, one of today’s changes was about making a view controller method do less by factoring object creation and error handling into its collaborators. The resulting code handles far less of the action involved. Instead, it delegates the action to a new command-like object. And instead of querying an event template for data and assembling an actual event with start and end dates, it delegates event creation to the template itself. Tell, Don’t Ask saved the day.

Continue reading …