我想覆盖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 '_'
发布于 2016-02-18 16:46:54
你不能重写赋值,但你可以在你的情况下使用不同的运算符。例如&=
运算符。
func &= (inout left: CGFloat, right: Float) {
left = CGFloat(right)
}
因此,您可以执行以下操作:
var A: CGFLoat = 1
var B: Float = 2
A &= B
顺便说一句,swift中存在运算符&+
、&-
和&*
。它们表示没有溢出的C风格的操作。More
发布于 2021-04-15 17:29:02
这不是operator loading
方法。但是结果可能是你所期望的。
// 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)
https://stackoverflow.com/questions/29964177
复制相似问题