Search code examples
iosswiftenumsswift3

Check if a value is present in enum or not


Following is my enum

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

Want to check if a value is present in enum or not? How to do it?


Solution

  • You can simply try to initialize a new enumeration case from your string or check if all cases contains a rawValue equal to your string:

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