swift的流程控制结构包括了C的for , while , switch, 以及objective-c中增加的for - in
而其中的用法有所不同的是switch在 Swift 中的用法.
1.在for - in的循环中如果不会用到每一次取得值可以用”_”代替
var answer = 1
for _ in 1...5 {
answer * = 2
}
2.由于swift中新加入了元组的概念所以对于字典的遍历变得简单了
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
//字典的键key解读为animalName ,字典的值会被解读为legCount
3.while循环在swift 2.0把do - while改为了 repeat - while 但是其用法没有改变
4.条件语句
当匹配的case块中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个case块。这也就是说,不需要在case块中显式地使用break语句。,如果想强制执行下一个case 的话需要添加fallthrough关键字 ,而且switch中必须要有default否则会报错
在switch 中支持值绑定: 就是case的块的模式允许将匹配的值绑定到一个临时的饿常量或变量,这些常量或变量在该case块里就可以被引用了
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println ("on the x-axis with an x value of \(x)")
case (0, let y):
println ("on the y-axis with an y value of \(y)")
case let (x, y):
println ("somewhere else at (\(x), \(y))")
}//由于最后一个case块匹配了余下所有可能的值,switch语句就已经完备了,因此不需要再书写默认块。
在case块中可以使用where语句来判断额外的条件
let otherPoint = (1, -1)
switch otherPoint {
case let(x, y) where x == y
println("(\(x), \(y)) is on the line x == y")
default:
println("(\(x), \(y)) isn't on the line x == y")
}
5.控制转移语句 fallthrough关键字用法
使用fallthrough关键字之后, 在执行完一个case之后,会自动落入到下一个case分支中
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer."
值得注意的是: fallthrough关键字不会检查它下一个将会落入执行的case中的匹配条件。fallthrough简单地使代码执行继续连接到下一个case中的执行代码,这和C语言标准中的switch语句特性是一样的。
6. 在swift中可以在循环体和switch代码块中嵌套循环体和switch代码块来创造复杂的控制流结构。所以对于break 和 continue在使用时要指明是针对哪一个的, 在swift中可以使用标签来实现, 带上标签可以控制该标签代表对象的中断或者执行.
产生一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,并且该标签后面还需带着一个冒号。
label name: while animal { //给animal 写上了一个标签
switch name{
case "dog":
println ("it's a \(name)")
case "pig":
break name //结束while循环而不是switch
default:
println ("it's a animal")
}