6

协议类型“Any”的值不能符合“Equatable”;只有结构/枚举/类类型可以符合协议

值是类型“ANY”,因为它可以是 Int 或 String。所以无法实现 Equatable 协议。

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

2 回答 2

4

我有一个类似的问题,解决方案是使用[AnyHashable]而不是[Any]类型!

于 2021-05-22T23:18:35.967 回答
2

使用泛型而不是任何...

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

  }
}
于 2020-05-02T17:15:33.477 回答