Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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' operands".

func add<T>(num1: T,num2: T) -> T {
    return num1 + num2
}
like image 488
user2749248 Avatar asked Dec 07 '15 02:12

user2749248


2 Answers

Swift doesn't know that the generic type T has a '+' operator. You can't use + on any type: e.g. on two view controllers + doesn't make too much sense

You can use protocol conformance to let swift know some things about your type!

I had a go in a playground and this is probably what you are looking for :)

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

func add<T: Addable>(num1: T, _ num2: T) -> T {
    return num1 + num2
}

extension Int: Addable {}
extension Double: Addable {}
extension Float: Addable {}

add(3, 0.2)

Let me know if you need any of the concepts demonstrated here explained

like image 90
Adam Campbell Avatar answered Oct 16 '22 07:10

Adam Campbell


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

func add<T: Numeric>(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.

like image 23
Paul Solt Avatar answered Oct 16 '22 07:10

Paul Solt