Joe Blow Joe Blow - 1 year ago 71
Swift Question

Swift 3, customize the "=" equals operator ? (Not equality, "==")

I have a class

public class Thing

like this

var blah:Thing = "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 = "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?

Answer Source

You can't override the = operator in Swift:


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++, but it really shouldn't be, in most cases. It adds needless smoke and mirrors to your code, with all kinds of confusing implicit behaviour.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download