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

后端 未结 3 1357
感动是毒
感动是毒 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:41

    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

提交回复
热议问题