Advanced Operator in Types

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

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

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.

Infix operator especially

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?

3 Likes

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 self.property == other.property
    }
    func ==(lhs: Type, rhs: Type) -> Bool {
        print(self) // Okay, we have “lhs” and “rhs”, but then what is “self”?!?
        return lhs.property == rhs.property
    }
}
_ = 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.

1 Like