[swift-evolution] Proposals: (1) Forbidding custom `==` for value types, (2) `dispatch` keyword, (3) `default`-result for methods with `Self`, and (4) Poor-Mans-Existentials

Brent Royal-Gordon brent at architechies.com
Sun Jul 17 08:11:13 CDT 2016


> On Jul 14, 2016, at 1:36 PM, Johannes Neubauer via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 1. Custom implementation of equals operator `==` for value types should be forbidden. Rationale: Why has it been added in the first place? For omitting some values from the equals test?

This limitation would prevent you from even implementing IEEE floating-point semantics (+0.0 == -0.0, while NaN != NaN; neither would be allowed by this rule). It would similarly prevent you from implementing even moderately 

> Properties pointing at reference types should be tested with `===`.

This rule in particular would also prevent you from implementing Equatable semantics for most of the copy-on-write containers (String, Array, Set, Dictionary), which all use an internal reference to a memory buffer. And several of Foundation's struct wrappers, like the `Data` type that wraps `NSData`. And any value type of your own which contains a lot of internal data and which, after a lot of testing and benchmarking, you determine would be more efficiently implemented as a value type wrapping a reference type with copy-on-write semantics. And who knows what else.

Ultimately, it boils down to this:

> If a value instance is equal to another, but the value may differ... this is odd semantics.

Equality is how we define whether two instances differ: If `==` returns `true`, then they don't differ. Now, there are some important commonsense rules about this—two `==` instances should have virtually identical behavior—but you can't just ignore the widespread need for this feature. If Swift didn't offer `Equatable` overloading, we would have to invent it ourselves—most likely with some sort of half-baked workaround that would cause confusion about whether you ought to use "pure" equality or "smart" equality in any given situation. Think of the `==` vs. `===` mess in JavaScript and you'll get an idea of what I mean.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list