首页 > 解决方案 > Swift 模式匹配 - 保护中的多个枚举大小写模式?

问题描述

使用枚举案例和守卫以允许多个案例继续进行的正确语法是什么?

通过 aswitch我们可以使用case-item-list来组合 switch case。

有没有类似的 for guardor ifstatements?

这是我想做的有点像的代码示例...

enum Thingy {
    case one
    case two
    case three
}

func doSomething(with value: Thingy) {
    switch value {
    case .one, .three:
        print("I like these numbers")
    default:
        print("Two")
    }
}

// Doesn't compile
func doSomethingAlt(with value: Thingy) {
    guard .one, .three = value else {
        print("Two")
        return
    }

    print("I like these numbers")
}

标签: swiftswitch-statementguard-statement

解决方案


您只需要给出由OR( ||) 条件分隔的条件。方法如下:

func doSomethingAlt(with value: Thingy) {
    guard value == .one || value == .three else {
        print("Two")
        return
    }

    print("I like these numbers")
}

这将要求enum符合Equatable. Enums没有关联值或raw-type自动符合Equatable. 由于Swift 4.1即使具有关联类型的枚举案例也会自动符合Equatable. 这是一些代码:

enum Thingy: Equatable {
    case one(String)
    case two
    case three
}
func doSomethingAlt(with value: Thingy) {
    guard value == .one("") || value == .three else {
        print("Two")
        return
    }

    print("I like these numbers")
}

而且,由于Swift 5.1枚举关联类型可以具有默认值。这是一个很棒的功能,所以你只需要这样做:

enum Thingy: Equatable {
    case one(String = "")
    case two
    case three
}
func doSomethingAlt(with value: Thingy) {
    guard value == .one() || value == .three else {
        print("Two")
        return
    }

    print("I like these numbers")
}

推荐阅读