swift中的运算符实现

问题描述 投票:1回答:1

在以下使用运算符+=的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

swift operators swift-protocols
1个回答
0
投票

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

相反,你应该像这样通用它:

func +=<T: Value>(a:inout T, b:Value) {
    let t = a.get() + b.get()
    a.set(to:t)
}
© www.soinside.com 2019 - 2024. All rights reserved.