[swift-evolution] Derived Equatable conformance akin to Codable
Dave Abrahams
dabrahams at apple.com
Tue May 30 15:07:34 CDT 2017
on Fri May 26 2017, Logan Shire <swift-evolution at swift.org> wrote:
> Given we now have precedent in the form of the derived Codable conformance coming in Swift 4.0,
> it begs the question why we don’t offer the same behavior for value types that declare themselves to
> be Equatable
> and have all Equatable properties. E.g.
>
> struct A: Equatable {
> let foo: String
> let bar: Int
> }
>
> struct B: Equatable {
> let baz: Double
> }
>
> struct C: Equatable {
> let a: A
> let b: B
> }
>
> let a = A(foo: “hello”, bar: 1)
> let a2 = A(foo: “hello”, bar: 2)
> a == a2 // false
> let b = B(baz: 3.1)
> let c = C(a: a, b: b)
> le c2 = C(a: a2, b: b)
> c == c2 // false
>
> You would always be free to shadow the provided implementation:
>
> extension A {
> func ==(lhs: A, rhs: A) {
> return lhs.foo == rhs.foo
> }
> }
>
> a == a2 // true
>
> It’s up for debate whether this should apply to reference types, or Hashable, but at a bare minimum
> we should
> offer it for value types consisting of Equatable value types that explicitly declare but don’t
> implement the conformance.
As a convenience, someone could write
extension Equatable where Self : Codable {
static func == (lhs: Self, rhs: Self) -> Bool {
// serialize lhs and rhs and compare the archives.
}
}
That would probably function (if not necessarily perform) almost as
well.
--
-Dave
More information about the swift-evolution
mailing list