# 从零开始Swift之控制流

### 循环

#### For-In 循环

``````for index in 1...5 {
print("\(index) times 5 is \(index * 5))")
}
``````

#### For-In 遍历数组

``````let names = ["Anna","Alex","Brain","Jace"]
for name in names {
print("\(name)");
}
``````

### while 循环

``````let finalSquare = 25
var board = [Int](repeatElement(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
while square < finalSquare {
diceRoll += 1
if diceRoll == 7 {
diceRoll = 1
}
square += diceRoll
if square < board.count {
square += board[square];
}
}
print("Game over!")
``````

### repeat-while循环, "while" 循环是线判断条件, 后执行循环体, repeat-while循环是先执行一次循环体, 然后判断条件, 再循环, 直到条件为假

``````//repeat {
//    ....
//} while ....
``````

### 条件语句

#### if

``````var temperatureInfahrenheit = 30
if temperatureInfahrenheit <= 32 {
print("It's very cold. consider waring a scarf")
}

temperatureInfahrenheit = 40
if temperatureInfahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}else{
print("It's not that cold. Wear a t-shirt")
}
``````

### Switch

#### swift中的switch 中case条件将不再仅仅限制于Int型, 多种类型都可以当做case条件

``````let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
``````

#### 每个case 后面必须接一个执行代码否则会报错

``````let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
print("The letter A")
default:
print("Not the letter A")
}
``````

#### 一次匹配多个条件, 多个条件现在一个case里, 使用","隔开

``````let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a","A":
print("The letter A")
default:
print("Not the letter A")
}
// case 的条件可以是一个范围
let approxmateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String
switch approxmateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings)")
``````

#### 使用元组当做条件

``````let somePoint = (1,1)
switch somePoint {
case (0,0):
print("(0,0)在坐标原点上")
case (_,0):
print("(\(somePoint.0),0) 在x轴上")
case (0,_):
print("(0,\(somePoint.1) 在y轴上)")
case (-2...2,-2...2):
print("(\(somePoint.0), \(somePoint.1) 在矩形里)")
default:
print("(\(somePoint.0), \(somePoint.1) 在矩形外)")
}
``````

### 一个switch case 可以绑定一个或多个值匹配的临时常量或者变量, 用于case的主体. 此行为称为值绑定

``````let anotherPoint = (2,0)
switch anotherPoint {
case (let x, 0):
print("在x轴上有一个x值是\(x)")
case (0, let y):
print("在y轴上有一个y值是\(y)")
default:
print("")
}
``````

#### switch case 可以使用where子句来检查附加条件

``````let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x),\(y) 在 x == y的线上)")
case let (x, y) where x == -y:
print("(\(x),\(y) 在 x == -y的线上)")
default:
print("")
}
``````

### 控制转移语句

• continue
• break
• fallthrough
• return
• throw

#### 就是告诉代码,当前代码已完成,进行下一次循环

``````let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a","e","i","o","u"]
for character in puzzleInput.characters{
if charactersToRemove.contains(character) {
continue
}else{
puzzleOutput.append(character)
// 结果是 grt mnds thnk lk

}
}
``````

#### 此行为可用于匹配和忽略switch语句中的一个或多个case。 因为Swift的switch语句是详尽的，不允许空的情况，有时需要故意匹配和忽略一个case，以使你的意图显式。 你可以通过将break语句写为你想要忽略的整个案例来做到这一点。 当该情况由switch语句匹配时，case中的break语句立即结束switch语句的执行。

``````let numberSymbol: Character = "三"
var possibleInterValue:Int?
switch numberSymbol {
case "1", "١", "一":
possibleInterValue = 1
case "2","二":
possibleInterValue = 2
case "3","三":
possibleInterValue = 3
case "4","四":
possibleInterValue = 4
default:
break
}
if let integerValue = possibleInterValue {
print("The integer value of \(numberSymbol) is \(integerValue).")
}else{
print("An integer could not be found for \(numberSymbol)")
}
``````

#### Swift中的switch语句不会通过每个case的底部，并进入下一个。 相反，整个switch语句在第一个匹配大小写完成后立即完成执行。 相比之下，C要求在每个开关情况结束时插入一个明确的break语句，以防止fallthrough。 避免默认fallthrough意味着Swift switch语句比它们在C中的同行更简洁和可预测，因此他们避免错误地执行多个switch case。如果您需要C风格的突发行为，您可以根据具体情况选择采用关键字逐渐减少的行为。

``````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."
}
print(description)
// The number 5 is prime number, and also an integer
``````

#### 带标签的语句通过将标签放置在与语句的介绍者关键字相同的行上，后跟冒号来指示

``````var count = 0
loop: while count < 10{
count += 1
if count == 5 {
continue loop
}
}
``````

### if let 与 guard let

#### `if var` 连用, `{}` 可以对值进行修改!

``````if var name = oName,
let age = oAge{
name = "老李"
print(name + String(age))
}
``````

#### guard let 守护一定有值, 如果没有直接返回

``````guard let name = oName, let age  = oAge else {
print("姓名或年龄为 nil")
return

}
// 代码执行至此, name 和 age 一定有值!
// 通常判断是否有值后, 会做具体的逻辑实现, 通常代码多!
// 如果用 if let 凭空多了一层分支, guard 是降低分支层次的办法
// guard 的语法是 Swift 2.0 推出的!
print(name + String(age))
``````

#### `if let`和 `guard let`命名技巧

• ==使用同名的变量接收值, 在后续使用的都是非控制, 不需要解包==
• ==好处, 可以避免起名字的烦恼==
``````func demo(name: String?, age: Int?) {
guard let name = name, let age = age else {
return
}
print(name + String(age))
}
``````

#### 检查API的可用性

``````if #available(iOS 10, macOS 10.12, *){
// 在iOS平台上只能使用iOS 10或更高版本的API,并且在macOS上只能使用macOS 10.12 或更高版本的API
}else{

}
``````