简体   繁体   中英

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. following are the code snipped.

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 textVlaue:String {
   Switch self {
     case x:
        return "x"
     case y:
        return "y"
   }
}
}

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

  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM