Synthesizing Comparable, for enums

This idea is by no means completely fleshed out, but one could imagine synthesized == for a type being replaced by a default implementation implemented in terms of something like KeyPathIterable:

// pseudo-ish code
static func == (lhs: Self, rhs: Self) -> Bool {
  for keyPath in Self.allKeyPaths {
    guard lhs[keyPath: keyPath] == rhs[keyPath: keyPath] else { return false }
  }
  return true
}

There's still a ton of unknown details and unanswered questions here though, such as:

  • How do we express the condition that this conformances should only apply to types whose properties are all Equatable? Right now there's no way to write that constraint.
  • If KeyPathIterable can be customized by users, how would that impact a proposed implementation based on it?
  • Can the compiler optimize the loop out to make it just as efficient as a sequence of conditional expressions?
  • What about enums? How would we express the same concept over their associated values?

The trick seems to be figuring out how to get the compiler to expose the metadata that's needed using a convenient set of metaprogramming primitves so folks can write general algorithms in terms of those. (So, hygienic macros, I guess?)

3 Likes