Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
mcfly soft Avatar asked Apr 30 '15 09:04

mcfly soft


People also ask

How do you overload an assignment operator?

Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we'll get to. The assignment operator must be overloaded as a member function. This will call f1. operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves.

Is operator overloading supported in Swift?

Operator overloading is a powerful feature of Swift that can make development much more efficient, if you do it with care.

What is operator overloading in Swift?

Swift supports operator overloading, which is a fancy way of saying that what an operator does depends on the values you use it with. For example, + sums integers like this: let meaningOfLife = 42 let doubleMeaning = 42 + 42. But + also joins strings, like this: let fakers = "Fakers gonna " let action = fakers + "fake"

Can we overload address of operator?

You cannot overload the following operators: . You cannot overload the preprocessor symbols # and ## . An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.


Video Answer


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

like image 135
Antonio Avatar answered Oct 06 '22 13:10

Antonio