Swift编程基础(四):控制流

来源:互联网 发布:海贼王好看的小说知乎 编辑:程序博客网 时间:2024/05/16 10:34

For循环

For-In

我们可以使用for-in循环来遍历一个集合里的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符。                                          
for index in 1...3{     print(index)}//1//2//3
index是一个每次循环遍历开始时被自动赋值的常量,这种情况下,index在使用前不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明。
let base = 3let power = 3var answer = 1for _ in 1...power{answer = base * answer   print(answer)}//3//9//27
如果我们不需要知道区间内每一项的值,可以使用下划线(_)替代变量名来忽略对值的访问。

For条件递增

//格式一:for(var i=0;i<3;i++){    print(i)}//格式二:for var i=0;i<3;++i {    print(i)}//备注:格式二中的++i不能写成i++,否则报错。如果想写成i++,就用格式一。

Switch

Swift里面的switch与OC中的语句不同。在Swift中,当匹配的case分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个case分支。也就是说,不需要在case分支中显示得使用break语句。既然Swift里面的switch语句有这样的特性,那么如果想要达到贯穿执行怎么办呢?使用***fallthrough***关键字;
let someCharacter: Character = "e"switch someCharacter {case "a", "e", "i", "o", "u":    print("\(someCharacter) is a vowel")case "b", "c", "d", "f", "g", "h", "j", "k", "l","m","n", "p", "q", "r", "s", "t", "v", "w", "x", "y","z":    print("\(someCharacter) is a consonant")default:    print("\(someCharacter) is not a vowel or a consonant")} //输出:e is a vowel 
let anotherCharacter: Character = "a"switch anotherCharacter {case "a":case "A":     print("The letter A")default:     print("Not the letter A")}//这么写,在OC里对,在Swift里报错
let anotherCharacter: Character = "a"switch anotherCharacter {case "a":    fallthroughcase "A":    print("The letter A")default:    print("Not the letter A")}//好吧,加上贯穿关键字:fallthrough,输出:The letter A

Switch的区间匹配

let count = 30let countedThings = "stars in the Milky Way"var naturalCount: Stringswitch count {case 0:     naturalCount = "no"case 1...9:     naturalCount = "a few"case 10...99:     naturalCount = "tens of"case 100...999:     naturalCount = "hundreds of"default:     naturalCount = "thousands and millions of"}print("There are \(naturalCount) \(countedThings).")//输出:There are tens of stars in the Milky Way.

Switch与元组

元组中下划线(_)可以用来匹配所有可能的值
let somePoint = (1, 1)switch somePoint {case (0, 0):     print("(0, 0) is at the origin")case (_, 0):     print("(\(somePoint.0), 0) is on the x-axis")case (0, _):     print("(0, \(somePoint.1)) is on the y-axis")case (-2...2, -2...2):     print("(\(somePoint.0), \(somePoint.1)) is inside the box")default:     print("(\(somePoint.0), \(somePoint.1)) is outside of the box")}//输出:(1, 1) is inside the box
在上面的例子中,switch语句会判断某个点是否是原点(0,0),是否在想轴上,是否在Y轴上,是否在一个以原点为中心的4*4的矩形里,或者在这个矩形外面。不像OC语言,Swift允许多个case匹配同一个值。也就是说,点(0,0)其实可以匹配前四个case,但是首先匹配case(0,0),因此剩下的能够匹配的case分支都会被忽略掉。

Switch的值绑定

case分支的模式允许将匹配的值绑定到一个临时的变量或常量,这些常量或变量在该case分支里就可以被引用了——这种行为被称为值绑定。
let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0):     print("on the x-axis with an x value of \(x)")case (0, let y):     print("on the y-axis with a y value of \(y)")case let (x, y):     print("somewhere else at (\(x), \(y))")}//输出:on the x-axis with an x value of 2
0 0
原创粉丝点击