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\'
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(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