如何在swift中重载赋值运算符 [英] how to overload an assignment operator in swift
问题描述
我想覆盖CGFloat的'='运算符,如下面的尝试:
I would like to override the '=' operator for a CGFloat like the follow try :
func = (inout left: CGFloat, right: Float) {
left=CGFloat(right)
}
所以我可以做以下事情:
So I could do the following:
var A:CGFloat=1
var B:Float=2
A=B
可以这样做吗?我收到错误通过分配给'_'
Can this be done ? I get the error Explicitly discard the result of the closure by assigning to '_'
推荐答案
这是不可能的 - 如文档:
That's not possible - as outlined in the documentation:
无法重载默认赋值运算符( =)。只能复用赋值运算符。类似地,三元条件运算符(a?b:c)不能重载。
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.
如果这不能说服你,只需改变运营商 + =
:
If that doesn't convince you, just change the operator to +=
:
func += (inout left: CGFloat, right: Float) {
left = CGFloat(right)
}
并且您会注意到您将不再收到编译错误。
and you'll notice that you will no longer get a compilation error.
误导性错误消息的原因可能是因为编译器正在解释您的重载尝试作业
The reason for the misleading error message is probably because the compiler is interpreting your attempt to overload as an assignment
这篇关于如何在swift中重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!