How do I add two generic values in Swift?

。_饼干妹妹 提交于 2020-12-12 01:07:02

问题


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.


回答1:


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

should be enough.

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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/30046669/how-do-i-add-two-generic-values-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!