Swift教程之控制流详解

2020-01-08 22:47:32王旭

default:
println("(someCharacter) is not a vowel or a consonant")
}
// prints "e is a vowel"
在这个例子中,首先看这个字符是不是元音字母,再检测是不是辅音字母。其它的情况都用default来匹配即可。

 

不会一直执行

跟C和Objective-C不同,Swift中的switch语句不会因为在case语句的结尾没有break就跳转到下一个case语句执行。switch语句只会执行匹配上的case里的语句,然后就会直接停止。这样可以让switch语句更加安全,因为很多时候编程人员都会忘记写break。

每一个case中都需要有可以执行的语句,下面的例子就是不正确的:

 

复制代码
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// this will report a compile-time error
跟C不同,switch语句不会同时匹配a和A,它会直接报错。一个case中可以有多个条件,用逗号,分隔即可:

 

 

复制代码  
switch some value to consider {
case value 1,
value 2:
statements
}
范围匹配

 

switch语句的case中可以匹配一个数值范围,比如:

 

复制代码  
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are (naturalCount) (countedThings).")
// prints "There are millions and millions of stars in the Milky Way."

 

元组

case中还可以直接测试元组是否符合相应的条件,_可以匹配任意值。