分支语句

if语句的格式:

if 条件 {} else {}

if 条件 {} else if 条件 {} else {}

条件要求是一个Bool类型的值

Swift要求{}中只有一条语句,{}也不能省略

switch语句的格式:

switch 分支因子{

case 值1:

响应1

case 值2,

值3:

响应2和3

...

default:

其他处理

}

Swift中case语句不需要用break结尾

case可以支持:

简单的字面值,如:

var cardType = "大陆通行证"

switch cardType {

case "大陆通行证":

print("请去1号柜台办理")

case "台湾通行证":

print("请去2号柜台办理")

case "美国通行证","日本通行证":

print("请去3号柜台办理")

default:

print("请去4号柜台办理")

}

元组,如:

var stu = ("东大", 2014)

switch stu {

case ("东大", _):

print("东北大学 2014")

case ("沈师", _):

print("沈阳师范大学 2013")

case ("辽大", _):

print("辽宁大学 2015")

default:

print("其他")

}

区间,如:

var ascii:Int = 50

switch ascii {

case 48..<58:

print("数字")

case 65...90,97...122:

print("字母")

default:

print("符号")

}

值绑定和条件值绑定,如:

var pos = (110, 10)

switch pos {

case let (x, 20):

print("坐标:(\(x),20)")

case let (x, y) where x == y :

print("坐标对角线:(\(x):\(y))")

case let (x, y) where x<20 || x>100:

print("不再中心位置:(\(x):\(y))")

default:

print("其他位置")

}

let (x, 20) 是“值绑定”

let (x, y) where x ==y 是“条件绑定”

“值绑定”还可以用于if语句


for循环

形式一:

for 循环因子 in 集合 {}

循环因子,不需要let和var这样的关键字

集合包括:数组、字典、区间等

形式二:

for 初始化因子; 条件; 自变运算{}

这里的因子必须是变量


while循环

形式一:

while 条件 {}

形式二:

do {} while 条件


continue

用法一:

单独的continue

用法二:

continue Label

如:

for1: for a in 1...5 {

for2: for b in 1...10 {

if a == b {

continue for1

}

print("a=\(a) b=\(b)")

}

}

break

用法一:

单独使用break

用法二:

break Label

for1: for a in 1...5 {

for2: for b in 1...10 {

if 3*a == b {

break for1

}

print("a=\(a) b=\(b)")

}

}

用法三:

switch的case中,作为空行占位

var pos = (110, 10)

switch pos {

case let (x, 20):

print("坐标:(\(x),20)")

case let (x, y) where x == y :

print("坐标对角线:(\(x):\(y))")

case let (x, y) where x<20 || x>100:

break

default:

break

}

fallthrogh

用于实现C语言中,case后面没有break的情况

var pos = (110, 10)

switch pos {

case let (x, 20):

print("坐标:(\(x),20)")

case let (x, y) where x == y :

print("坐标对角线:(\(x):\(y))")

case let (x, y) where x<20 || x>100:

print("不再中心位置:(\(x):\(y))")

fallthrough

default:

print("其他位置")

}