HenryRootTwo
HenryRootTwo

Reputation: 2612

How do I add two generic values in 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.

Upvotes: 6

Views: 9854

Answers (4)

Yuvrajsinh
Yuvrajsinh

Reputation: 4584

This also can be achieved using extension like this

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element {
        return reduce(.zero, +)
    }
}

And can be used like this

let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
// arraySum == 16.5

let rangeSum = (1..<10).sum()
// rangeSum == 45

You can refer documentation for more details https://developer.apple.com/documentation/swift/additivearithmetic#declaration

Upvotes: 1

Sweeper
Sweeper

Reputation: 272845

Since Swift 5, there is a built in AdditiveArithmetic protocol which you can constrain to:

func sum<T: AdditiveArithmetic >(array:Array<T>) -> T{
    var acc = T.zero
    for t in array{
        acc = acc + t
    }
    return acc
}

Now you don't need to manually conform the built-in types to a protocol :)

Upvotes: 5

DirectX
DirectX

Reputation: 952

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))")

Upvotes: 5

Sunkas
Sunkas

Reputation: 9590

protocol Numeric {
    func +(lhs: Self, rhs: Self) -> Self
}

should be enough.

Source: http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/

Upvotes: 6

Related Questions