Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add two generic values in Swift?

Tags:

generics

swift

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.

like image 460
HenryRootTwo Avatar asked Mar 17 '23 04:03

HenryRootTwo


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/

like image 138
Sunkas Avatar answered Mar 30 '23 10:03

Sunkas


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))")
like image 25
DirectX Avatar answered Mar 30 '23 11:03

DirectX