【问题标题】:find an enum type in an array在数组中查找枚举类型
【发布时间】:2017-11-20 12:47:37
【问题描述】:

如果我有这个枚举:

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

【问题讨论】:

    标签: ios swift enums


    【解决方案1】:

    为了使其更具可读性,您可以像这样在枚举中添加一个函数:

    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】:

      如果你让你的枚举相等,你可以做这样的事情......

      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】:

        并非如此,但您可以在枚举上定义一个帮助程序,以使其在调用站点上不那么粗暴。

        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 }
        

        【讨论】:

          猜你喜欢
          • 2021-09-17
          • 2013-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-14
          • 2017-01-14
          相关资源
          最近更新 更多