How do you know that T
is a type that can be added? T
can be anything, can't it? What if T
is Bool
? True
and False
values can certainly not be added.
To be able to add T
s, the range of possible types for T
must be limited. T
must conform to the Numeric
protocol. Since the Numeric
protocol defines a +
operator, we can be sure that whatever T
is, as long as it conforms to Numeric
, it can be added.
You could do something like this:
func sum<T: Numeric>(_ array: [T]) -> T {
return array.reduce(0, +)
}
Or an extension:
extension Sequence where Element : Numeric {
func sum() -> Element {
return reduce(0, +)
}
}
Note that in both cases, I have put a : Numeric
constraint.
T
should have+