Swift学习笔记(二)控制流

1. for-in循环
[c]
for index in 1…5 {
print("\(index) times 5 is \(index * 5)")
}
[/c]
2. while循环,repeat-while循环
[c]
while condition {
statements
}
repeat {
statements
} while condition
[/c]
3. if条件
[c]
if condition {
statements
} else if condition2 {
statements
} else {
statements
}
[/c]
4. switch-case-default条件
[c]
// swift中不存在隐式贯穿,break不是必须
// 如果需要贯穿,使用fallthrough关键字
/*
反例:
case "a": // 无效,这个分支下面没有语句
case "A":
正例:
case "a", "A":
正例:
case "a":
fallthrough
case "A":
*/
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
case 4..<6: //支持区间
case (0, 0): //支持元组
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
default:
otherwise, do something else
}
[/c]
值绑定
[c]
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))")
case let (x, y) where x == y: //可以使用where判断额外的条件
}
// 输出 "on the x-axis with an x value of 2"
[/c]
5. 控制转移语句
continue
break
fallthrough
return
throw
6. 带标签的语句
※循环嵌套非常有用
蛇和梯子游戏
游戏的规则如下:
游戏盘面包括 25 个方格,游戏目标是达到或者超过第 25 个方格;
每一轮,你通过掷一个六面体骰子来确定你移动方块的步数,移动的路线由上图中横向的虚线所示;
如果在某轮结束,你移动到了梯子的底部,可以顺着梯子爬上去;
如果在某轮结束,你移动到了蛇的头部,你会顺着蛇的身体滑下去。
[c]
import UIKit

let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
gameLoop: while square != finalSquare {
diceRoll = (Int)(arc4random()%6)+1
print(diceRoll)
switch square + diceRoll {
case finalSquare:
// 骰子数刚好使玩家移动到最终的方格里,游戏结束。
break gameLoop
case let newSquare where newSquare > finalSquare:
// 骰子数将会使玩家的移动超出最后的方格,那么这种移动是不合法的,玩家需要重新掷骰子
continue gameLoop
default:
// 合法移动,做正常的处理
square += diceRoll
square += board[square]
}
}
print("Game over!")
[/c]
7. guard语句
※代码简洁利器
[c]
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(["name": "John"])
// 输出 "Hello John!"
// 输出 "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// 输出 "Hello Jane!"
// 输出 "I hope the weather is nice in Cupertino."
[/c]
8. 检测API可用性
[c]
if #available(iOS 10, macOS 10.12, *) {
// 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
} else {
// 使用先前版本的 iOS 和 macOS 的 API
}
[/c]