Search code examples
arraysswiftcomputed-propertiesprotocol-extensionprotocol-inheritance

Computed property to sum numeric arrays in Swift


Task from book says: without calling reduce(_: _:) method, sum sequences of numbers by adding a computed property called sum. You should be able to use it like this:

[3, 7, 7].sum            // 17
[8.5, 1.1, 0.1].sum      // 9.7

Hint by authors: in developer documentation check what protocols do Int and Double conform to, and what protocols do those protocols inherit from. Within below code I just kind of combined two solutions I found, however it still contains method reduce. If you can help me to understand how this can be solved / which part of developer documentation provides a clue. Also how can I avoid error in current code / apply possible solution on closed range.

extension Sequence where Element: Numeric {
    var sum: Any {
        return reduce(0, +)
    }
}

[3, 7, 7].sum
[8.5, 1.1, 0.1].sum
[1...4].sum // Error: Property 'sum' requires that 'ClosedRange<Int>' conform to 'Numeric'

Solution

  • [1...4].sum is working on an Array of ClosedRange ([...] mean "Array of..."). You meant: (1...4).sum.

    You also mean:

       var sum: Element { ... }
    

    rather than Any.

    If you want to make it even more generic, you can move from Numeric up to AdditiveArithmetic this way:

    extension Sequence where Element: AdditiveArithmetic {
        var sum: Element { reduce(.zero, +) }
    }
    

    That way it could work on things like vectors.