[swift-evolution] Operator implementation inside struct/class body

Haravikk swift-evolution at haravikk.me
Mon Feb 1 03:47:39 CST 2016


> On 1 Feb 2016, at 04:55, Chris Lattner <clattner at apple.com> wrote:
> 
> We need multiple modules to be able to define instances of an operator, we need operators in extensions, and we need retroactive conformance to work, as with any other member.

Why? Like I say, the operator itself is really static, not a method of an instance, as it declares what it operates on in its parameters, just as an operator does now, the only difference is being able to declare it in class/struct for clarity. There’s also no talk of making explicit operator declarations such as Foo.==(a, b), so it seems to me that nothing will actually change functionally from the way operators are now. A class/struct conforms to an operator requirement if an operator with the appropriate signature exists.

We only need to consider shadowing etc. if we want to instead change operators to be instance methods where the operation is applied to self plus any other optional values, e.g-

	class Foo {
		func ==(rhs:Foo) {
			return self.someProperty == rhs.someProperty
		}
	}

But that would require operator declarations to be completely redesigned, as opposed to the proposal which simply asks for something like:

	class Foo {
		static func ==(lhs: Foo, rhs:Foo) {
			return lhs.someProperty == rhs.someProperty
		}
	}

Which is essentially identical to the things are now, only the declaration happens to be grouped with a type, rather than declared globally like we have now.

That said, this does raise an interesting point, as in the second example there’s nothing stopping you from declaring an operator in type Foo that has no relevance to it whatsoever (e.g- an operator involving IntegerTypes). So redesigning into instance methods may be desirable as that way the implicit parameter (self) is definitely relevant to the type where the operator is implemented. In that case yes, it would probably need to use the same rules for resolving shadowing/overrides, treating the implicit parameter as the target of the operation (so usually the value on the left, except for prefix operators).


More information about the swift-evolution mailing list