微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检查枚举中是否存在值

如何解决检查枚举中是否存在值

以下是我的枚举

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

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

解决方法

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

let string = "categories"

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

if HomeDataType.allCases.contains(where: { $0.rawValue == string }) {
    print(true)
}
,

使用 rawValue 初始化枚举将返回一个可选值,因此您可以尝试解包它

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

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

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

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

依赖 init 返回 nil 的解决方案很糟糕,因为:

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。