How to implement generic sum function for SequenceType where Generator.Element is of type Int

generics, swift

Solution

The constraint should be `S.Generator.Element == Int`:

func sum<S: SequenceType where S.Generator.Element == Int>(s: S) -> Int {
    var sum = 0
    for i in s {
        sum += i
    }
    return sum
}

Slightly more general for integer types:

func sum<S: SequenceType, T : IntegerType where S.Generator.Element == T >(s: S) -> T {
    var sum : T = 0
    for i in s {
        sum += i
    }
    return sum
}

Problem

I’m trying to write a function used in benchmarking the iteration performance of various SequenceType implementations. It should simply sum the contents of the sequence, where all elements are `Int`s. I’m struggling with expressing the generic constraint on the function... ``` func sum<S: SequenceType where S.Generator.Element: Int>(s: S) -> Int { var sum = 0 for i in s { sum += i } return sum } ``` This results in following two errors: - Type `‘S.Generator.Element’` constrained to non-protocol type `’Int’` - Binary operator `'+=‘` cannot be applied to operands of type `’Int'` and `’S.Generator.Element’` Is there a way to define this function to work over any `SequenceType` implementation, with elements specialized to `Int`?

Original source