Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of protocol type 'Any' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols

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"
        }
    }
}
like image 609
pankaj nigam Avatar asked May 02 '20 16:05

pankaj nigam


People also ask

Can a protocol conform to Equatable Swift?

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.

What is Equatable protocol in Swift?

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.


2 Answers

I had a similar issue, where using [AnyHashable] instead of [Any] type was the solution!

like image 165
Top-Master Avatar answered Nov 07 '22 16:11

Top-Master


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"
    }

  }
}
like image 23
Jawad Ali Avatar answered Nov 07 '22 14:11

Jawad Ali