Avoid Equatable and Hashable Boilerplate, Swift 4.2

Avoid Equatable and Hashable boilerplate, Swift 4.2

You could write your custom template via Stencil markup language and autogenerate the code using the Sourcery library.

Or use the existing solutions (AutoEquatable, AutoHashable Sourcery templates).

And also you could write something like this:

protocol IHash: class { }

extension IHash where Self: Hashable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}

class User: IHash, Hashable {
var name: String = ""

func hash(into hasher: inout Hasher) {
hasher.combine(self.name)
}
}

It will help you to avoid duplication in different classes.

Why Hashable protocol forces variable to be comply with Equatable protocol?

Because any use of hashing to locate objects (e.g. in a Dictionary) needs to handle hashing collisions - that is when different (unequal) objects have the same hash value.

When that happens, there needs to be a way to check objects for equality.



Related Topics



Leave a reply



Submit