swift中的运算符实现

时间:2017-12-23 22:28:19

标签: swift operators swift-protocols

在以下带有运算符+=的shift操场中,我收到编译错误:

protocol Value {
    func get() -> Float
    mutating func set(to:Float)
}

func += (a:inout Value, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}

struct S : Value {
    var t:Float
    func get() -> Float {
        return t
    }
    mutating func set(to:Float) {
        t = to
    }
}

var s1 = S(t:3)
let s2 = S(t:4)
s1 += s2 // Compiler error: Binary operator '+=' cannot be applied to two 'S' operands

现在,如果我将运营商重新定义为

func += (a:inout S, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}

它运作得很好。为什么我不能将左侧的+=定义为Value

1 个答案:

答案 0 :(得分:0)

正如@Hamish在评论中所述,您不能将协议Value用于inout变量,因为被调用的函数可以自由地分配其他Value的实例。符合类型。

相反,你应该把它变成这样的通用:

func +=<T: Value>(a:inout T, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}