Check if a value is present in enum or not

Viewed 3756

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?

5 Answers

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

Initialize enum using rawValue will return an optional, so you can try to unwrap it

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

You can add static method to your enum, which attempts to create instance of the enum and returns if it succeeded or not

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

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

Simpliest solution. You don't need CaseIterable protocol for that.

guard let type = HomeDataType(rawValue: string) else { return }
switch type {
    case .questions:
    ...
}
Related