'how to overload an assignment operator in swift
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 '_'
Solution 1:[1]
That's not possible - as outlined in the 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.
If that doesn't convince you, just change the operator to +=
:
func +=(left: inout 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
Solution 2:[2]
You can not override assignment but you can use different operators in your case. For example &=
operator.
func &= (inout left: CGFloat, right: Float) {
left = CGFloat(right)
}
So you could do the following:
var A: CGFLoat = 1
var B: Float = 2
A &= B
By the way operators &+
, &-
, &*
exist in swift. They represent C-style operation without overflow. More
Solution 3:[3]
This is not operator overload
approach. But the result may be what you are expecting
// 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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kelin |
Solution 2 | |
Solution 3 |