问题描述
在项目中,我们将类用于模型的图层,因此,我必须编写如下代码:
On project we are using classes for model's layer and because of that I have to write code like this:
// MARK: - Hashable
extension Player: Hashable {
static func == (lhs: Player, rhs: Player) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.name)
}
}
可以以某种方式避免这种样板吗?默认情况下是否可以实现Equatable
与.hashValue
进行比较?谢谢.
Can this boilerplate can be somehow avoided? Is it possible to implement that Equatable
compare by .hashValue
by default? Thanks.
推荐答案
您可以通过Stencil标记语言编写自定义模板,并使用Sourcery库自动生成代码.
You could write your custom template via Stencil markup language and autogenerate the code using the Sourcery library.
或使用现有解决方案(AutoEquatable,AutoHashable Sourcery模板).
Or use the existing solutions (AutoEquatable, AutoHashable Sourcery templates).
您也可以这样写:
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.
这篇关于避免使用Equatable和Hashable样板,Swift 4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!