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

前端 未结 3 507
孤独总比滥情好
孤独总比滥情好 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:29

    You should do as that answer suggested. Create a protocol for your use and extend all of the classes that you want to use it. Then make sure T implements that protocol in your method signature.

    You can't use an "addable" protocol because there isn't one in swift. The swift library actually creates a function + for each valid addition operations. Command-click on something like Int to see where all of these are defined. It will look something like this:

    //....
    func +(lhs: Int8, rhs: Int8) -> Int8
    func +(lhs: UInt16, rhs: UInt16) -> UInt16
    func +(lhs: Int16, rhs: Int16) -> Int16
    func +(lhs: UInt32, rhs: UInt32) -> UInt32
    func +(lhs: Int32, rhs: Int32) -> Int32
    //etc...
    

提交回复
热议问题