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.

Browse the blog archive