extension Sequence where Element: Numeric {
public func sum() -> Element {
return reduce(0, +)
}
}
extension Sequence {
public func sum<T>() -> T where T: Numeric, Element == T? {
var sum: T = 0
for value in self {
if let value = value {
sum += value
}
}
return sum
}
}
But when I use the method, I get ambiguity errors:
*****:70:24: error: ambiguous reference to member 'sum()'
XCTAssertEqual(series.sum(), 948.872)
^~~~~~
Statistics.Sequence:2:17: note: found this candidate
public func sum() -> Self.Element
^
Statistics.Sequence:2:17: note: found this candidate
public func sum<T>() -> T where T : Numeric, Self.Element == T?
If there's a more specific name you can give your operation, that would avoid the ambiguity. Otherwise, you should be able to specify the type of the result you expect using as, series.sum() as Double, to force it to pick the method that returns Double rather than Double?.
But, please note, both methods return Double (not an optional). I would like the same method to work both for a sequence of Numeric and a sequence of Optional<Numeric>.