【问题标题】:Compound switch cases: may we have a single common value binding for compound enum cases that have the same type of associated value?复合开关案例:我们可以为具有相同类型关联值的复合枚举案例提供单个公共值绑定吗?
【发布时间】:2017-05-06 05:35:55
【问题描述】:

(当我准备好并且几乎写完问题时,重新阅读相应的语言指南部分为我回答了它,但可能问答对其他人有用,所以我还是会发布它)

背景

考虑以下enum,具有两种不同类型的关联值之一,IntString

enum Foo {
    case bar(Int)
    case baz(Int)
    case bax(Int)
    case fox(String)
}

当在switch 语句中执行模式匹配时,我们可能会构建复合案例,每个案例都包含几种可能的匹配模式(如果任何模式匹配,则进入case 分支):

func foo(_ foo: Foo) -> Int {
    switch foo {
        case .bar, .baz, .bax: return 42
        case .fox: return 0
    }
}

就像非复合案例一样,复合案例也可能包括值绑定:

func foo(_ foo: Foo) -> Int {
    switch foo {
        case .bar(let x), .baz(let x), .bax(let x): return x 
        case .fox(let y): return Int(y) ?? 0
    }
}

// or
func foo(_ foo: Foo) -> Int {
    switch foo {
        case let .bar(x), let .baz(x), let .bax(x): return x 
        case let .fox(y): return Int(y) ?? 0
    }
}

问题

  • 是否可以对复合案例使用单个公共值绑定,它涵盖具有相同类型关联值的多个 enum 案例的复合?

例如,在上面的后一个值绑定示例中,以某种方式为复合 case 中的公共类型关联值使用单个绑定功能

// not valid
func foo(_ foo: Foo) -> Int {
    switch foo {
        case .bar, .baz, .bax, (let x): return x 
        case .fox: return 0
    }
}

【问题讨论】:

    标签: swift enums switch-statement


    【解决方案1】:

    不,这是不可能的;在上面的值绑定示例中,x 必须绑定在每个模式中,并且对于复合案例中的每个模式都必须单独保留。

    引用Language Guide - Control Flow [强调我的]

    复合案例还可以包括值绑定。的所有图案 复合案例必须包含相同的值绑定集,并且 每个绑定必须从所有的 复合案例中的模式。这确保了,无论哪个部分 的复合案例匹配,案例主体中的代码可以 始终访问绑定的值,并且该值始终具有 同一类型。

    如果我们尝试在上面的复合示例中省略其中一种模式中的绑定,我们会收到一条关于该主题的不言自明的错误消息:

    func foo(_ foo: Foo) -> Int {
        switch foo {
            case .bar(_), .baz(let x), .bax(let x): return x 
            case .fox: return 0
        }
    }
    
    error: 'x' must be bound in every pattern
    

    即使我们在后面的正文中不使用x,这仍然成立

    func foo(_ foo: Foo) -> Int {
        switch foo {
            case .bar(_), .baz(let x), .bax(let x): return 0 
            case .fox: return 0
        }
    } // same error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多