Binary operator '+' cannot be applied to two 'T' operands

后端 未结 3 1386
感动是毒
感动是毒 2020-12-31 04:12

I am using Generics to add different types like Int, Double, Float, etc. I used the code below but I\'m getting error \"Binary operator \'+\' cannot be applied to two \'T\'

3条回答
  •  长情又很酷
    2020-12-31 04:45

    In Swift 4 / Xcode 9+ you can take advantage of the Numeric protocol.

    func add(num1: T, num2: T) -> T {
        return num1 + num2
    }
    
    print(add(num1: 3.7, num2: 44.9)) // 48.6
    print(add(num1: 27, num2: 100))  // 127
    

    Using this means you won't have to create a special protocol yourself.

    This will only work in the cases where you need the functionality provided by the Numeric protocol. You may need to do something similar to @adam's answer for % and other operators, or you can leverage other protocols provided by Apple in the Xcode 9 SDK.

提交回复
热议问题