[swift-evolution] Universal Equatability, Hashability, and Comparability

Sean Heber sean at fifthace.com
Wed Mar 9 12:59:24 CST 2016


> We can also allow opt-in by adopting a protocol, eg `struct SimpleStruct: DefaultEquatable`. DefaultEquatable would tell the compiler to auto-generate an equatable implementation. Similar for DefaultHashable.
> 
> In the C# world you’d actually do something like this with an attribute. I know user-defined attributes aren’t on the table right now but some more built-in ones would be sufficient: @defaultEquatable, @defaultHashable, etc. 
> They could even take a list of properties to ignore if such a feature were useful: `@defaultEquatable(ignored: [currentDate, randomInt])`.

Might be interesting if you could pass in parameters when you declare conformance, like:

struct MyType : Equatable(default) {}

If “default” was missing, you’d have to supply the relevant ==/equals function or whatever as usual, but if it was there you’d get automatically generated stuff based on documented rules.

Maybe it could even be extensible so you can define protocol extensions that are “named” and only apply if you declare conformance with the relevant name:

protocol Bar {
  func barFunction()
}

extension Bar(foo) {
  func fooFunction() { }
}

struct Type1 : Bar(foo) {
  func barFunction() {}
}

struct Type2 : Bar {
  func barFunction() {}
}

A Type1 instance would also have a fooFunction(), but a Type2 instance would not.

Using this you could have multiple default implementations defined for the same protocol depending on circumstances.

extension Bar(scenerio1) {
  func barFunction() { print(“1”) }
}

extension Bar(scenerio2) {
  func barFunction() { print(“2") }
}

struct Thing1 : Bar(scenerio1) {}
struct Thing2 : Bar(scenerio2) {}

let a: Bar = Thing1()
let b: Bar = Thing2()

a.barFunction() -> “1”
b.barFunction() -> “2”

:)

l8r
Sean



More information about the swift-evolution mailing list