Advanced Operator in Types

(Genaro Chris) #1

Why can't an operator be declared as an instance member?

(Svein Halvor Halvorsen) #2

Can you give an example of what you’re trying to accomplish?

(Erik Little) #3

It's just not how Swift was designed. In theory it should be possible to turn any method that takes a single param into a "operator", and this is what Scala does. Swift made the initial decision that operators are defined statically, and only on a strict subset of characters, rather than any method can be used as an operator like Scala. Swift restricts operators to a certain character set to make it easier on parsing and tooling.

(Genaro Chris) #4

Infix operator especially

(Svein Halvor Halvorsen) #5

If I understand you correctly, you want a () -> T instance method to work as a prefix/suffix operator, and a (Self) -> T instance method to work as an infix operator.

This proposal is accepted, but not implemented. If if ever gets implemented, and if I understand it correctly, it would treat any instance method (Self) -> T as a static method (Self, Self) -> T (instead of the current (Self) -> (Self) -> T as is today). That might make it possible to use instance methods as operators?

(Jeremy David Giesbrecht) #6

Is your question is why you have to write this...

static func ==(lhs: Self, rhs: Self) -> Bool { ... }

...and not just this...

func ==(lhs: Self, rhs: Self) -> Bool { ... }


If so, the answer is that there is no “self” instance in an operator usage context.

struct Type {
    func isEqual(to other: Type) -> Bool {
        // “self” makes sense here.
        return ==
    func ==(lhs: Type, rhs: Type) -> Bool {
        print(self) // Okay, we have “lhs” and “rhs”, but then what is “self”?!?
        return ==
_ = a.isEqual(to: b) // “self” is clearly “a”.
_ = a == b // “self” is ...?!?

Because there can be no meaningful instance, the operator function is declared like any other method not tied to a particular instance—static.