如何在 swift 中重载赋值运算符

问题描述 投票:0回答:3

我想重写 CGFloat 的“=”运算符,如下所示:

func = (inout left: CGFloat, right: Float) {
    left=CGFloat(right)
}

所以我可以执行以下操作:

var A:CGFloat=1
var B:Float=2
A=B

这可以做到吗?我收到错误

Explicitly discard the result of the closure by assigning to '_'

ios swift operator-overloading
3个回答
34
投票

这是不可能的 - 正如文档中所述:

无法重载默认赋值运算符 (=)。仅复合赋值运算符可以重载。同样,三元条件运算符 (a ? b : c) 也不能重载。

如果这还不能说服您,只需将运算符更改为

+=
:

func +=(left: inout CGFloat, right: Float) {
    left += CGFloat(right)
}

您会注意到,您将不再收到编译错误。

产生误导性错误消息的原因可能是因为编译器将您的重载尝试解释为赋值


12
投票

您不能覆盖分配,但您可以根据您的情况使用不同的运算符。例如

&=
运算符。

func &= (inout left: CGFloat, right: Float) {
    left = CGFloat(right)
}

因此您可以执行以下操作:

var A: CGFLoat = 1
var B: Float = 2
A &= B

顺便说一句,运算符

&+
&-
&*
存在于 swift 中。它们代表没有溢出的 C 风格操作。 更多


1
投票

这是不是

operator overload
的方法。但结果也许就是你所期待的

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        // String has an initializer that takes an Int, we can use that to
        // create a string
        self = String(value)
    }
}

extension Int: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = Int(value) ?? 0
    }
}

// No error, s2 is the string "4"
let s1: Int = "1"
let s2: String = 2

print(s1)       //output: 1
print(s2)       //output: 2
print(s1 + 2)   //output: 3 instead of "12"
© www.soinside.com 2019 - 2024. All rights reserved.