协议类型“Any”的值不能符合“Equatable”;只有 struct/enum/class 类型可以符合协议

pan*_*gam 8 enums struct ios swift equatable

协议类型“Any”的值不能符合“Equatable”;只有 struct/enum/class 类型可以符合协议

值的类型为“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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Top*_*ter 6

我遇到了类似的问题,使用[AnyHashable]而不是[Any]类型是解决方案!


use*_*632 2

使用泛型而不是 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"
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 请评论 downVote 的原因...以便我可以在遗漏某些内容时进行改进 (2认同)