swift 中的运算符实现
operator implementations in swift
在以下带运算符 +=
的 shift playground 中,出现编译错误:
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
?
正如@Hamish 在评论中所述,您不能将协议 Value
用于 inout
变量,因为被调用的函数可以自由分配其他一些实例 Value
符合它的类型。
相反,您应该像这样使其通用:
func +=<T: Value>(a:inout T, b:Value) {
let t = a.get() + b.get()
a.set(to:t)
}
在以下带运算符 +=
的 shift playground 中,出现编译错误:
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
?
正如@Hamish 在评论中所述,您不能将协议 Value
用于 inout
变量,因为被调用的函数可以自由分配其他一些实例 Value
符合它的类型。
相反,您应该像这样使其通用:
func +=<T: Value>(a:inout T, b:Value) {
let t = a.get() + b.get()
a.set(to:t)
}