Home » Swift » how to overload an assignment operator in swift

how to overload an assignment operator in swift

Posted by: admin November 30, 2017 Leave a comment

Questions:

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 '_'

Answers:

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 += (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

Questions:
Answers:

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