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

2

8

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"
        }
    }
}
Timisoara answered 2/5, 2020 at 16:43 Comment(0)
A
6

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

Amid answered 22/5, 2021 at 23:18 Comment(0)
L
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"
    }

  }
}
Lynelllynelle answered 2/5, 2020 at 17:15 Comment(3)
please comment reason of downVote ... so that i can improve if missing somethingLynelllynelle
Why do we need two function. 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 }Timisoara
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 ...Lynelllynelle

© 2022 - 2024 — McMap. All rights reserved.