7

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"
        }
    }
}
pkamb
  • 33,281
  • 23
  • 160
  • 191
pankaj nigam
  • 381
  • 1
  • 6
  • 9

2 Answers2

6

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

Top-Master
  • 7,611
  • 5
  • 39
  • 71
2

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

  }
}
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • 2
    please comment reason of downVote ... so that i can improve if missing something – Jawad Ali May 02 '20 at 17:59
  • Why do we need two function. static func == (lhs: BusinessDetail, rhs: BusinessDetail) -> Bool { lhs.cellType == rhs.cellType } static func == (lhs: BusinessDetail, rhs: BusinessDetail) -> Bool { lhs.cellType == rhs.cellType && lhs.value == rhs.value } – pankaj nigam May 03 '20 at 01:27
  • this is the requirement of a struct that is Generic + equitable .... As this T should also be equitable so you need to write two functions .. hope it helps ... – Jawad Ali May 03 '20 at 09:56