2

I have a class

public class Thing

like this

var blah:Thing
blah.name = "text"

it occurred to me, it would be fantastic if I could just "override the equals sign", when the item on the right is a string.

Then you could have

var blah:Thing
var x:Thing

blah = "text"   // Swift knows I mean blah.name = "text"
blah = x        // Swift knows I mean blah becomes x as normal

Am I missing something obvious? How to do?

Note that you can of course take over the subscript operation, using public subscript which is fantastic. Can you take over the "=" equals sign?

Fattie
  • 27,874
  • 70
  • 431
  • 719
  • 3
    Are you looking for this: [Swift struct initialization, making another struct like String](http://stackoverflow.com/questions/40373776/swift-struct-initialization-making-another-struct-like-string)? – (But you can't override the `=` operator.) – Martin R Nov 02 '16 at 19:22
  • 3
    [how to overload an assignment operator in swift](http://stackoverflow.com/questions/29964177/how-to-overload-an-assignment-operator-in-swift). – Martin R Nov 02 '16 at 19:30
  • @MartinR - incredible. That is awesome for initialization!!!! – Fattie Nov 02 '16 at 19:58

1 Answers1

4

You can't override the = operator in Swift:

NOTE

The tokens =, ->, //, /*, */, ., the prefix operators <, &, and ?, the infix operator ?, and the postfix operators >, !, and ? are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.

It can be done in C++, mostly as a consequence of the manual memory management required. Thanks to ARC, this isn't necessary in Swift, and it would just add needless smoke and mirrors to your code, with all kinds of confusing implicit behaviour.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 1
    Shame... Wanted to override `a: Float = b: CGFloat` and vice versa so I don't have to cast around all the time.... – Lord Zsolt Jul 23 '18 at 21:17
  • 1
    @LordZsolt That cast is lossy. It would be unwise to obscure that behind a custom assignment operator. – Alexander Jul 23 '18 at 21:18
  • Yeah, I guess you have a point, that it could cause unwanted side effects if it's applied to every part of the project. But if you have a UI architectural stack that's separate from the math heavy business logic, I see no harm in it. – Lord Zsolt Jul 23 '18 at 21:24