Swift:具有多个模式的切换案例无法绑定到变量 [英] Swift: Switch case with multiple patterns cannot bind to variable

查看:28
本文介绍了Swift:具有多个模式的切换案例无法绑定到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在官方 Swift 编程语言 指南,关于 switch case 是这样说的:...如果 case 包含多个与控制表达式匹配的模式,则这些模式都不能包含常量或变量绑定."

In the official Swift Programming Language guide, it has this to say about switch case: "...if the case contains multiple patterns that match the control expression, none of those patterns can contain constant or variable bindings."

包含多个模式是什么意思?

What does it mean by containing multiple patterns?

推荐答案

表示有多个模式的 case 标签不能声明变量.

It means that case labels with multiple patterns cannot declare variables.

这是允许的:

let somePoint = (1, 1)
switch somePoint {
// Case with multiple patterns without binding
case (0, _),
     (_, 0):
    println("(\(somePoint.0), \(somePoint.1)) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

这也是允许的:

let somePoint = (1, 1)
switch somePoint {
// Case with single patterns with binding
case (0, let y):
    println("(0, \(y)) is on an axis")
case (let x, 0):
    println("(\(x), 0) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

但是,这是被禁止的:

let somePoint = (1, 1)
switch somePoint {
// Case with multiple patterns that have bindings
case (0, let y),
     (let x, 0):
    println("(\(x), \(y)) is on an axis")
default:
    println("(\(somePoint.0), \(somePoint.1)) is not of an axis")
}

以上产生一个错误:

error: 'case' labels with multiple patterns cannot declare variables

这篇关于Swift:具有多个模式的切换案例无法绑定到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆