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

时间:2020-05-02 16:43:10

标签: ios swift struct enums 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 textVlaue:String {
   Switch self {
     case x:
        return "x"
     case y:
        return "y"
   }
}
}

1 个答案:

答案 0 :(得分: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"
    }

  }
}