如何在 swift 中重载赋值运算符
how to overload an assignment operator in swift
我想重写 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 '_'
这是不可能的 - 如 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.
如果这不能说服您,只需将运算符更改为 +=
:
func +=(left: inout CGFloat, right: Float) {
left += CGFloat(right)
}
你会发现你不会再遇到编译错误。
产生误导性错误消息的原因可能是因为编译器将您的重载尝试解释为赋值
您不能覆盖赋值,但可以根据您的情况使用不同的运算符。例如 &=
运算符。
func &= (inout left: CGFloat, right: Float) {
left = CGFloat(right)
}
因此您可以执行以下操作:
var A: CGFLoat = 1
var B: Float = 2
A &= B
顺便说一下,运算符 &+
、&-
、&*
存在于 swift 中。它们代表了没有溢出的 C 风格操作。 More
这不是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)
print(s2)
print(s1 + 2)
我想重写 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 '_'
这是不可能的 - 如 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.
如果这不能说服您,只需将运算符更改为 +=
:
func +=(left: inout CGFloat, right: Float) {
left += CGFloat(right)
}
你会发现你不会再遇到编译错误。
产生误导性错误消息的原因可能是因为编译器将您的重载尝试解释为赋值
您不能覆盖赋值,但可以根据您的情况使用不同的运算符。例如 &=
运算符。
func &= (inout left: CGFloat, right: Float) {
left = CGFloat(right)
}
因此您可以执行以下操作:
var A: CGFLoat = 1
var B: Float = 2
A &= B
顺便说一下,运算符 &+
、&-
、&*
存在于 swift 中。它们代表了没有溢出的 C 风格操作。 More
这不是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)
print(s2)
print(s1 + 2)