【问题标题】:Check if a value is present in enum or not检查枚举中是否存在值
【发布时间】:2021-05-12 09:36:03
【问题描述】:

以下是我的枚举

enum HomeDataType: String, CaseIterable {
  case questions           = "questions"
  case smallIcons          = "smallIcons"
  case retailers           = "retailers"
  case products            = "products"
  case banners             = "banners"
  case single_product      = "single_product"
  case single_retail       = "single_retail"
  case categories          = "categories"
  case airport             = "All_Airport"
  case single_banner       = "single_banner"
  case none                = "none"
}

想检查枚举中是否存在值吗?怎么做?

【问题讨论】:

  • 您的问题不清楚。你的意思是如果“横幅”是一个有效值?你可以做HomeDataType.init(rawValue: "banners") 并检查它是否是nil。或者您有一个具有多个可能值的 HomeDataType,然后您需要一个 OptionSet,但可能需要进行其他更改。

标签: ios swift enums swift3


【解决方案1】:

依赖 init 返回 nil 的解决方案不好,因为:

Enum initialized with a non-existent rawValue does not fail and return nil

swift 团队没有在任何地方记录这种行为,它显示了语言和团队的糟糕程度

【讨论】:

    【解决方案2】:

    您可以将静态方法添加到您的枚举中,该方法会尝试创建枚举的实例并在成功与否时返回

     static func isPresent(rawValue: String) -> Bool {
        return HomeDataType(rawValue: rawValue) != nil
     }
    
     HomeDataType.isPresent(rawValue: "foobar") // false
     HomeDataType.isPresent(rawValue: "banners") // true
    

    【讨论】:

    • 你可以扩展RawRepresentable并创建一个泛型方法extension RawRepresentable {static func contains(_ rawValue: RawValue) -> Bool {Self.init(rawValue: rawValue) != nil}}
    【解决方案3】:

    使用 rawValue 初始化枚举会返回一个可选项,所以你可以尝试解开它

    if let homeDataType = HomeDataType (rawValue: value) {
        // Value present in enum
    } else {
        // Value not present in enum
    }
    

    【讨论】:

      【解决方案4】:

      您可以简单地尝试从您的字符串中初始化一个新的枚举案例,或者检查所有案例是否包含一个等于您的字符串的rawValue

      let string = "categories"
      
      if let enumCase = HomeDataType(rawValue: string) {
          print(enumCase)
      }
      
      if HomeDataType.allCases.contains(where: { $0.rawValue == string }) {
          print(true)
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 2017-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多