代码之家  ›  专栏  ›  技术社区  ›  Daniel Murali

在数组中查找枚举类型

  •  2
  • Daniel Murali  · 技术社区  · 8 年前

    如果我有这个枚举:

    enum TestEnum {
        case typeA
        case typeB(Int)
    }
    

    这个阵列: let testArray = [TestEnum.typeB(1), .typeA, .typeB(3)]

    是否有一种比以下方法更简单的方法来确定该数组中是否包含项:

    if testArray.contains(where: {if case .typeA = $0 { return true }; return false}) {
        print("contained")
    } else {
        print("not found")
    }
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   Bruno    8 年前

    为了使其更具可读性,可以向枚举中添加如下函数:

    enum TestEnum {
        case typeA
        case typeB(Int)
    
        static func ==(a: TestEnum, b: TestEnum) -> Bool {
            switch (a, b) {
            case (typeB(let a), .typeB(let b)) where a == b: return true
            case (.typeA, .typeA): return true
            default: return false
            }
        }
    }
    
    let testArray = [TestEnum.typeB(1), .typeA, .typeB(3)]
    
    if testArray.contains(where: { $0 == .typeA }) {
        print("contained")
    } else {
        print("not found")
    }
    
        2
  •  2
  •   Fogmeister    8 年前

    如果你使你的枚举相等,你可以这样做。。。

    enum TestEnum: Equatable {
        case testA
        case testB(Int)
    
        static func ==(lhs: TestEnum, rhs: TestEnum) -> Bool {
            switch (lhs, rhs) {
            case (.testA, .testA):
                return true
            case (.testB(let a), .testB(let b)):
                return a == b
            default:
                return false
            }
        }
    }
    
    let array: [TestEnum] = [.testA, .testB(1)]
    
    array.contains(.testA) // true
    array.contains(.testB(1)) // true
    array.contains(.testB(3)) // false
    

    这意味着您可以使用更简单的contains函数形式,而不必使用块。

        3
  •  1
  •   jefflovejapan    8 年前

    不完全是这样,但您可以在枚举上定义一个助手,使其在调用站点上不那么粗糙。

    enum TestEnum {
      case typeA
      case typeB(Int)
    
      var isTypeA: Bool {
        switch self {
          case .typeA:
          return true
          case .typeB:
          return false
        }
      }
    }
    
    let filtered: [TestEnum] = [.typeB(1), .typeA, .typeB(3)].filter { $0.isTypeA }