In Swift, how to generically limit function to types that understand T + T

前端 未结 3 533
孤独总比滥情好
孤独总比滥情好 2021-01-17 13:55

I would like to have a generic function that can use the plus operator on two values.

class funccalc {
    func doAdd(x:T,y:T) -> T {
        ret         


        
3条回答
  •  长发绾君心
    2021-01-17 14:22

    Have you tried using the protocol AdditiveArithmetic?

    https://developer.apple.com/documentation/swift/additivearithmetic

    Looks like thats exactly what you are looking for. That protocol has the method:

    static func + (Self, Self) -> Self

    Using your that protocol your method becomes:

    class funccalc {
        func doAdd(x:T,y:T) -> T {
            return x + y
        }
    }
    

提交回复
热议问题