-
Notifications
You must be signed in to change notification settings - Fork 1
5.Sourcery AutoEquatable AutoHashable
AliSoftware edited this page Sep 20, 2017
·
2 revisions
When you need to implement
Equatable
orHashable
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.
- Copy the
sourcery-0.8.0/Templates/AutoEquatable.stencil
&sourcery-0.8.0/Templates/AutoHashable.stencil
templates into yourCodeGenDemo/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 {}
- Start a build to make Sourcery generate the code
- Add the
AutoEquatable.generated.swift
andAutoHashable.generated.swift
files to yourCodeGenDemo/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
!
- Uncomment the code of the
func findDupes()
function on line 67 ofPersonListViewController.swift
- Notice the compiler error telling us that we can't create a
Set<Phone>
becausePhone
is notHashable
norEquatable
- Open
CodeGen/Sources/Model/Phone.swift
and make that struct conform toAutoEquatable
andAutoHashable
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 ==
norvar 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!