amodkanthe
amodkanthe

Reputation: 4530

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?

Upvotes: 6

Views: 9513

Answers (5)

Eduard
Eduard

Reputation: 310

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

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

Upvotes: 0

solutions relying on init returning nil are bad because:

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

swift team do not document this behavior anywhere and it shows how bad language and the team are

Upvotes: 0

Denis
Denis

Reputation: 1214

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

Upvotes: 3

aiwiguna
aiwiguna

Reputation: 2922

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
}

Upvotes: 3

Leo Dabus
Leo Dabus

Reputation: 236360

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

Upvotes: 11

Related Questions