Skip to content

Conversation

@calda
Copy link
Member

@calda calda commented Sep 30, 2024

Summary

This PR adds a new rule to prefer using a generated Equatable implementation when comparing all properties of a type. For structs, prefer using the compiler-synthesized Equatable implementation when possible.

This rule is implemented by the new redundantEquatable SwiftFormat rule added in nicklockwood/SwiftFormat#1891.

/// WRONG: The `static func ==` implementation is redundant and error-prone.
struct Planet: Equatable {
  let mass: Double
  let orbit: OrbitalElements
  let rotation: Double

  static func ==(lhs: Planet, rhs: Planet) -> Bool {
    lhs.mass == rhs.mass
      && lhs.orbit == rhs.orbit
      && lhs.rotation == rhs.rotation
  }
}

/// RIGHT: The `static func ==` implementation is synthesized by the compiler.
struct Planet: Equatable {
  let mass: Double
  let orbit: OrbitalElements
  let rotation: Double
}

/// ALSO RIGHT: The `static func ==` implementation differs from the implementation that 
/// would be synthesized by the compiler and compared all properties, so is not redundant.
struct CelestialBody: Equatable {
  let id: UUID
  let orbit: OrbitalElements

  static func ==(lhs: Planet, rhs: Planet) -> Bool {
    lhs.id == rhs.id
  }
}

Reasoning

Manually-implemented Equatable implementations are verbose, and keeping them up-to-date is error-prone. For example, when adding a new property, it's possible to forget to update the Equatable implementation to compare it.

--rules redundantGet
--rules redundantFileprivate
--rules redundantRawValues
--rules redundantEquatable
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will update to a new SwiftFormat build that includes this rule before merging

@calda calda requested review from bachand and miguel-jimenez-0529 and removed request for bachand October 3, 2024 17:22
@calda calda merged commit b879ec6 into master Oct 4, 2024
@calda calda deleted the cal--redundant-equatable-implementation branch October 4, 2024 11:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants