检查枚举中是否存在值

Check if a value is present in enum or not

以下是我的枚举

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

想要检查枚举中是否存在某个值?怎么做?

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

let string = "categories"

if let enumCase = HomeDataType(rawValue: string) {
    print(enumCase)
}

if HomeDataType.allCases.contains(where: { [=10=].rawValue == string }) {
    print(true)
}

使用 rawValue 初始化枚举将return一个可选的,所以你可以尝试解包它

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

您可以将静态方法添加到您的枚举中,它会尝试创建枚举的实例,returns 如果成功与否

 static func isPresent(rawValue: String) -> Bool {
    return HomeDataType(rawValue: rawValue) != nil
 }

 HomeDataType.isPresent(rawValue: "foobar") // false
 HomeDataType.isPresent(rawValue: "banners") // true

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

swift 团队没有在任何地方记录这种行为,这表明语言和团队有多么糟糕