Value of protocol type 'Any' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols
Value is type "ANY" as it can be Int or String. So not able to implement Equatable protocol.
struct BusinessDetail:Equatable {
static func == (lhs: BusinessDetail, rhs: BusinessDetail) -> Bool {
lhs.cellType == rhs.cellType && lhs.value == rhs.value
}
let cellType: BusinessDetailCellType
var value: Any?
}
enum BusinessDetailCellType:Int {
case x
case y
var textValue:String {
Switch self {
case x:
return "x"
case y:
return "y"
}
}
}
The short answer is that we can't. Each conforming type can be Equatable (in fact both our concrete types are) but we don't have a way of checking equality at the level of the protocol since the protocol does not declare any properties.
In Swift, an Equatable is a protocol that allows two objects to be compared using the == operator. The hashValue is used to compare two instances. To use the hashValue , we first have to conform (associate) the type (struct, class, etc) to Hashable property.
I had a similar issue, where using [AnyHashable]
instead of [Any]
type was the solution!
Use Generics instead of Any ...
struct BusinessDetail<T> {
let cellType: BusinessDetailCellType
var value: T?
}
extension BusinessDetail: Equatable {
static func ==<T> (lhs: BusinessDetail<T>, rhs: BusinessDetail<T>) -> Bool {
lhs.cellType == rhs.cellType
}
static func == <T1:Equatable>(lhs: BusinessDetail<T1>, rhs: BusinessDetail<T1>) -> Bool {
lhs.cellType == rhs.cellType && lhs.value == rhs.value
}
}
enum BusinessDetailCellType:Int {
case x
case y
var textVlaue:String {
switch self {
case .x:
return "x"
case .y:
return "y"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With