How do I add two common values ββin Swift?
I am trying to write a function to sum an array of numeric types. This is how I understood it:
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 behavior of the operator +
in the protocol Numeric
.
+3
source to share
2 answers
protocol Numeric {
func +(lhs: Self, rhs: Self) -> Self
}
should be enough.
Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/
+4
source to share
I did it like this, but I was just trying to add two values ββand not use an array, but thought it 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))")
-1
source to share