在 swift 中重载单个等于
Overload Single Equals in swift
我有一个奇怪的情况,我似乎无法让 single equals 过载
这很好用:
public func /=<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = (left.value / Double(right))
}
一旦我将其更改为:
public func =<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = Double(right)
}
我收到错误:
没有匹配运算符声明的运算符实现
我是否明显遗漏了什么疯狂的东西?
我试过中缀,但似乎没什么用。我以某种方式假设它的解释 = 错误?
恐怕没有骰子。来自 language reference
The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.
相反,如果您希望 ConvertibleUnit
始终可以从 Int
创建,请为协议提供一个 init(_ val: Int)
方法,以便人们可以编写 let unit = T(42)
。或者甚至可以考虑让它符合 IntegerLiteralConvertible
.
通常,Swift 中的首选样式是不在不同类型之间进行 automatic/implicit 转换。这就是为什么,例如,您必须先将 Int
转换为 Double
,然后才能将其添加到另一个 Double
。
当然可以这样写:
func +(lhs: Int, rhs: Double) -> Double {
return Double(lhs) + rhs
}
let i = 1
let f = 1.2
i + f // = 2.2
但这通常不被认为是好的做法。
如 Apple's official documentation、
中所述
It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.
您可以使用 infix
创建一个新的运算符,但遗憾的是您不能重载“=”。
我有一个奇怪的情况,我似乎无法让 single equals 过载
这很好用:
public func /=<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = (left.value / Double(right))
}
一旦我将其更改为:
public func =<T: ConvertibleUnit>(inout left: T, right: Int) {
left.value = Double(right)
}
我收到错误:
没有匹配运算符声明的运算符实现
我是否明显遗漏了什么疯狂的东西?
我试过中缀,但似乎没什么用。我以某种方式假设它的解释 = 错误?
恐怕没有骰子。来自 language reference
The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.
相反,如果您希望 ConvertibleUnit
始终可以从 Int
创建,请为协议提供一个 init(_ val: Int)
方法,以便人们可以编写 let unit = T(42)
。或者甚至可以考虑让它符合 IntegerLiteralConvertible
.
通常,Swift 中的首选样式是不在不同类型之间进行 automatic/implicit 转换。这就是为什么,例如,您必须先将 Int
转换为 Double
,然后才能将其添加到另一个 Double
。
当然可以这样写:
func +(lhs: Int, rhs: Double) -> Double {
return Double(lhs) + rhs
}
let i = 1
let f = 1.2
i + f // = 2.2
但这通常不被认为是好的做法。
如 Apple's official documentation、
中所述It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.
您可以使用 infix
创建一个新的运算符,但遗憾的是您不能重载“=”。