假设我有:
protocol MyError: Error, Equatable {
var errorDispalyTitle: String { get }
var errorDisplayMessage: String { get }
}
enum ContentState {
case .loading
case .error(any MyError)
case .contentLoaded
}
如果我在ContentState
中实现Equatable
以便我可以在单元测试期间进行比较,我最终会遇到一个问题,因为我必须比较两个any MyError
类型,这两个类型是盒装的,可能属于两个不同的底层类型.
extension ContentState: Equatable {
static func == (lhs: ContentState, rhs: ContentState) -> Bool {
switch (lhs, rhs) {
case (.loading, .loading):
return true
case (.contentLoaded, .contentLoaded):
return true
case (.error(let lhsError), .error(let rhsError)):
// TODO: have to compare if both underlying types are match and then if they are equal in value
default:
return false
}
}
}
我该怎么做呢?
我try 将泛型从存在类型提升到类型(例如ContentState<Error: MyError>
),这允许它在实现Equatable时编译,因为它知道如何推断类型,但问题是对于哪个类使用该枚举,接收它的类型并不重要,只有它是它的任何类型,如果我不实现any
存在类型,它就会开始要求泛型沿着链向上传播.