Home > database >  How can I compare two enums with OR operator?
How can I compare two enums with OR operator?

Time:11-07

I need to compare if any of the two cases meets the requirement, I need to take decision else need to do something else. I tried many ways and this is one of them but every way giving error.

if case .locked = itemStatus || case .hasHistoryLocked = itemStatus {
    print("YES")        
} else {
    print("NO")
}

CodePudding user response:

A switch is common pattern for matching a series of cases. See The Swift Programming Language: Enumerations: Matching Enumeration Values with a Switch Statement.

E.g.:

switch itemStatus {
case .locked, .hasHistoryLocked:
    print("YES")
default:
    print("NO")
}

CodePudding user response:

As your comment I see that you don't want to use Equatable to check enum. There is another way to check it using Enum rawValue

So it just like you get the rawValue of enum from the key and compare it with your itemStatus

enum Test : Int {
    case locked = 0
    case hasHistoryLocked = 1
    case anything = 2
}

let itemStatus = 0

if itemStatus == Test.locked.rawValue || itemStatus == Test.hasHistoryLocked.rawValue {
    print("Yes")
} else {
    print("No")
}
  • Related