I am trying to write a function to sum an array of numeric types. This is as far as I got:
protocol Numeric { }
extension Float: Numeric {}
extension Double: Numeric {}
extension Int: Numeric {}
func sum<T: Numeric >(array:Array<T>) -> T{
var acc = 0.0
for t:T in array{
acc = acc + t
}
return acc
}
But I don't know how to define the behaviour of the +
operator in the Numeric
protocol.
protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}
should be enough.
Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/
I did it like this but I was just trying to add two values and not using array but thought this might help.
func addTwoValues<T:Numeric>(a: T, b: T) -> T {
return a + b
}
print("addTwoValuesInts = \(addTwoValues(a: 3, b: 4))")
print("addTwoValuesDoubles = \(addTwoValues(a: 3.5, b: 4.5))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With