首页 > swift语言的switch句式中,fallthrough后面不能直接跟带有where的case子句吗?

swift语言的switch句式中,fallthrough后面不能直接跟带有where的case子句吗?

var x=1
switch x
{
case 1:
    println("x=1")
    fallthrough
case  let y where y==1:
    println("x==1")
default:
    println("default")
}

提示错误:

fallthrough cannot transfer control to a case label that declares variable

只能从字面上理解这句报错,谁能详细解释一下这个错误?


“fallthrough后面不能直接跟带有where的case子句吗?”
不是说不能接带有where的,是fallthrough后根本不能定义常量或变量。
http://blog.csdn.net/xieyupeng520/article/details/46764219


错误提示已经很明白了,fallthrough下面的那个case不能声明新变量、常量,也就是不能跳转到case后面接var或者let的语句的。

原因是因为fallthrough不会检查where匹配条件,这样便会导致var或者let声明的变量常量无法得到值,所以swift禁止fallthrough到这样的case中。

你可以把下面的语句提前就正确了。

var x=1
switch x
{   
case  let y where y==1:
    println("x==1")
    fallthrough
case 1:
    println("x=1")
default:
    println("default")
}
【热门文章】
【热门文章】