如何用OR操作符比较两个枚举?



我需要比较两种情况中是否有任何一种符合要求,我需要做出决定,否则需要做其他事情。我尝试了很多方法,这是其中之一,但每种方法都会出错。

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

switch是匹配一系列case的常用模式。参见Swift编程语言:Enumerations:用Switch语句匹配枚举值。

例如:

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

如果您想在ifguard语句中添加此语句,可以将上述内容包装在计算属性中。例如,

extension ItemStatus {
    var isLocked: Bool {
        switch self {
        case .locked, .hasHistoryLocked:
            return true
        default:
            return false
        }
    }
}

那么你可以这样做:

func doSomethingIfUnlocked() {
    guard !itemStatus.isLocked else {
        return
    }
    // proceed with whatever you wanted if it was unlocked
}

也可以为该类型添加Equatable一致性。假设ItemStatus是这样定义的:

enum ItemStatus {
    case locked
    case hasHistoryLocked
    case unlocked(Int)
}

现在,如果这是你的类型,你可以添加Equatable一致性:

enum ItemStatus: Equatable {
    case locked
    case hasHistoryLocked
    case unlocked(Int)
}

如果它不是你的类型,你不能简单地编辑原始声明,你可以改为添加Equatable一致性:

extension ItemStatus: Equatable {
    static func == (lhs: Self, rhs: Self) -> Bool {
        switch (lhs, rhs) {
        case (.locked, .locked), (.hasHistoryLocked, .hasHistoryLocked):                     // obviously, add all cases without associated values here
            return true
        case (.unlocked(let lhsValue), .unlocked(let rhsValue)) where lhsValue == rhsValue:  // again, add similar patterns for all cases with associated values
            return true
        default:
            return false
        }
    }
}

无论您如何将Equatable一致性添加到ItemStatus,您都可以这样做:

func doSomethingIfUnlocked() {
    guard itemStatus != .locked, itemStatus != .hasHistoryLocked else {
        return
    }
    // proceed with whatever you wanted if it was unlocked
}

正如你的评论,我看到你不想使用Equatable来检查enum。还有另一种方法来检查它使用Enum rawValue

就像你从关键字中获取enum的rawValue并将其与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")
}

最新更新