I have a struct that needs to be Decodable and Hashable. This struct has a property that is of a Protocol type. Depending on the type a concrete value of the protocol is filled in the struct. But how do I make this struct hashable without making the protocol Hashable (which makes it a Generic protocol which can't be directly used)?
enum Role: String, Decodable, Hashable {
case developer
case manager
....
}
protocol Employee {
var name: String { get }
var jobTitle: String { get }
var role: Role { get }
}
struct Manager: Employee, Hashable {
let name: String
let jobTitle: String
let role: Role = .manager
....
}
struct Developer: Employee, Hashable {
let name: String
let jobTitle: String
let role: Role = .developer
let manager: Employee // Here is the problem
static func == (lhs: Developer, rhs: Developer) -> Bool {
lhs.name == rhs.name &&
lhs.jobTitle == rhs.jobTitle &&
lhs.role == rhs.role &&
lhs.manager == rhs.manager // Type 'any Employee' cannot conform to 'Equatable'
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(jobTitle)
hasher.combine(role)
hasher.combine(manager) // Instance method 'combine' requires that 'H' conform to 'Hashable'
}
}
There are multiple issues with this:
- Just to make one property Hashable/Equatable we need to write the
==
andhash
function with all the properties. - Even though we do that, there is still a problem where the protocol is not Hashable/Equatable.
Is there some other or right way to do this?