#67: Constrained Extensions in Swift

Swift lets you add methods only when a generic type meets some extra condition.

extension Array where Element: Numeric {
    var sum: Element {
        reduce(0, +)
    }
}

Now sum exists only for arrays whose elements are numeric.

This is a great way to keep APIs focused and avoid offering methods that do not make sense for every specialization of a generic type.


I'm also on Twitter and GitHub.

Subscribe via RSS.