Skip to content

5.Sourcery AutoEquatable AutoHashable

AliSoftware edited this page Sep 20, 2017 · 2 revisions

Classroom Walkthrough (Part 5)

AutoEquatable, AutoHashable

When you need to implement Equatable or Hashable for many of your types, it can become quite cumbersome, and easy to forget the maintenance when you add new properties to those types. Sourcery is perfect for that use case too.

Step 5.1

  • Copy the sourcery-0.8.0/Templates/AutoEquatable.stencil & sourcery-0.8.0/Templates/AutoHashable.stencil templates into your CodeGenDemo/CodeGen/Templates folder:
cp sourcery-0.8.0/Templates/AutoEquatable.stencil CodeGenDemo/CodeGen/Templates/
cp sourcery-0.8.0/Templates/AutoHashable.stencil CodeGenDemo/CodeGen/Templates/

Notice that those templates use phantom protocols for opt-in to code generation, much like the AutoCases template we saw earlier. We'll have to create those.

  • Add the two necessary phantom protocol declarations to your CodeGenDemo/Sources/Protocols/SourceryProtocols.swift file:
protocol AutoEquatable {}
protocol AutoHashable {}

Step 5.2

  • Start a build to make Sourcery generate the code
  • Add the AutoEquatable.generated.swift and AutoHashable.generated.swift files to your CodeGenDemo/CodeGen/Generated group of your Xcode project
  • Look at the generated code: it's almost empty. It's time to make some types opt-in for AutoEquatable & AutoHashable!

Step 5.3

  • Uncomment the code of the func findDupes() function on line 67 of PersonListViewController.swift
  • Notice the compiler error telling us that we can't create a Set<Phone> because Phone is not Hashable nor Equatable
  • Open CodeGen/Sources/Model/Phone.swift and make that struct conform to AutoEquatable and AutoHashable to opt-in for code generation for it:
struct Phone: AutoEquatable, AutoHashable {
  
  • Rebuild: the previous error just disappeared and the code compiles now, without you having to write those func == nor var hash: Int!

Of course this would be even more interesting if we had more complex types with lots of properties to make Equatable & Hashable (here we only have 2), but you can guess the benefits!

➡️ Next Steps

Clone this wiki locally