我有一个关联值的枚举,出于测试目的,我想使它们相等,但不知道这种模式如何与具有多个参数的枚举一起工作。
例如,总结如下我知道使标题相等的语法。对于包含不同类型的多个值的选项,这将如何工作?
enum ViewModel {
case heading(String)
case options(id: String, title: String, enabled: Bool)
}
func ==(lhs: ViewModel, rhs: ViewModel) -> Bool {
switch (lhs, rhs) {
case (let .heading(lhsString), let .heading(rhsString)):
return lhsString == rhsString
case options...
default:
return false
}
}
我知道 Swift 4.1 可以为我们合成 Equatable 的一致性,但目前我无法更新到这个版本。
最佳答案
SE-0185 Synthesizing Equatable and Hashable conformance已在 Swift 4.1 中实现,因此它足以声明符合协议(protocol)(如果所有成员都是 Equatable
):
enum ViewModel: Equatable {
case heading(String)
case options(id: String, title: String, enabled: Bool)
}
对于早期的 Swift 版本,一个方便的方法是使用 tuples 可以与 ==
进行比较。
许多人还想在 Swift 版本检查中包含兼容性代码,以便在项目更新到 Swift 4.1 后使用自动合成:
enum ViewModel: Equatable {
case heading(String)
case options(id: String, title: String, enabled: Bool)
#if swift(>=4.1)
#else
static func ==(lhs: ViewModel, rhs: ViewModel) -> Bool {
switch (lhs, rhs) {
case (let .heading(lhsString), let .heading(rhsString)):
return lhsString == rhsString
case (let .options(lhsId, lhsTitle, lhsEnabled), let .options(rhsId, rhsTitle, rhsEnabled)):
return (lhsId, lhsTitle, lhsEnabled) == (rhsId, rhsTitle, rhsEnabled)
default:
return false
}
}
#endif
}
关于swift - 如何使关联值相等的 Swift 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51300121/