## Swift 邏輯控制之選擇結構
### `if - else if - else`
語法如下
```
if condition1 {
statements
} else if conditon2 {
statements
} else {
statements
}
```
> **注意:**
> 1. `if` 判斷的條件不強制使用 `()`擴起來。
> 2. 必須使用 `{}` 包含循環語句體。
### `switch - case - default`
語法如下
```
switch <#value#> {
case <#pattern#>:
<#code#>
case <#pattern2#>:
<#code2#>
default:
<#code#>
}
```
幾個舉例:
```
switch rating {
case "a","A":
print("Great!")
case "b","B":
print("Just So so!")
case "c","C":
print("Its Bad")
default:
print("Error")
}
// 使用switch判斷浮點數
let x = 2.5
switch x{
case 2.5:
print("I'm 2.5")
default:
print("I'm not 2.5")
}
// 使用switch判斷布爾值
let y = false
switch y{
case true:
print("I'm true")
case false:
print("I'm false")
}
```
> **注意:**
> 1. 和其他語言的語法不同的是,`switch` 不強制需要在每次執行完 `case` 中的語句后的寫 `break` 。
> 2. `switch` 語句如果不能完全窮舉完數據,那么必須寫 `default`。
> 3. 如果運行完一個 `case` 語句后想繼續運行下一個 `case` 語句,請添加 `fallthrough` 關鍵字。
### switch 的一些其他用法
#### 判斷范圍
```
let score = 9
switch score {
case 1..<60:
print("You got an egg!")
case 60:
print("Juse passed")
case 61 ..< 80:
print("Just so so!")
case 80 ..< 90:
print("Good!")
case 90 ..< 100:
print("Great!")
case 100:
print("Perfect!")
default:
print("Error.")
}
```
#### 判斷元組
判斷一個點在那個位置,比如 如果橫坐標是 0 ,那么我們就認為是在 x 軸坐標上。
```
let point: ( x: Int , y: Int ) = ( 0 , 1 )
switch point {
case ( 0 , 0 ):
print("It is origin!")
case ( _ , 0 ): // 忽略元祖數據
print("( \(point.x),\(point.y) ) is on the x-axis")
case ( 0 , _ ):
print("( \(point.x),\(point.y) ) is on the y-axis")
case ( -2...2 , -2...2 ): // 對于元祖元素使用區間運算符匹配
print("( \(point.x),\(point.y) ) is near the origin.")
default:
print("It is just an ordinary point")
}
```
#### 判斷并賦值
解包元組并賦值給常量。
```
let point: ( x: Int , y: Int ) = ( 1 , 0 )
switch point {
case ( 0 , 0 ) :
print("It is origin!")
case ( let x ,0 ) :
print("It is on the x-axis.")
print("The x value is \(x)")
case ( 0 , let y ):
print("It is on the y-axis.")
print("The y value is \(y)")
case ( let x , let y ):
print("It is just an ordinary point.")
print("The point is (\(x),\(y))")
}
```
#### `fallthrough` 關鍵字
```
let point: ( x: Int , y: Int ) = ( 0 , 0)
switch point {
case ( 0 , 0 ):
print("It is origin!")
fallthrough
case ( _ , 0 ):
print("( \(point.x),\(point.y) ) is on the x-axis")
fallthrough
case ( 0 , _ ):
print("( \(point.x),\(point.y) ) is on the y-axis")
default:
print("It is just an ordinary point")
}
```
上面的程序執行將打印出如下結果:
```
It is origin!
( 0,0 ) is on the x-axis
( 0,0 ) is on the y-axis
```
> Swift中的`switch case`和其他語言中的不同,它不是必須強制的使用`break`中斷上一次判斷,如果需要在判斷語句中使用類似c、c++、java類似的 `switch case` 判斷的效果,可以通過`fallthrough`關鍵字實現。使用這個關鍵字后,將在執行完當前分支成功后跳到下一個分支,而不是跳出判斷分支。
#### 控制轉移
查找 `x^4 - y^2 = 15 * x * y` 在300以內的正整數解。
我們可以很方便的使用`for in` 寫出程序代碼,如下:
```
var getAnswer = false
for m in 1...300 {
for n in 1...300 {
if m*m*m*m - n*n == 15*m*n {
print(m, n)
getAnswer = true
break
}
}
if getAnswer {
break
}
}
```
> 上面的代碼能很快的找出符合結果的答案,但是有太多的冗余代碼。
在Swift中,我們可以給循環取一個別名,在使用`break`、`continue`等關鍵詞時停止這個循環
```
findAnswer: for m in 1...300 {
for n in 1...300 {
if m*m*m*m - n*n == 15*m*n {
print(m, n)
break findAnswer
}
}
}
```
> 上面的循環將在找到一個符合的值之后跳出最外層的循環
### case 的一些用法
#### where 與匹配模式
語法如下
```
switch some value to consider {
case value1:
respond to value1
case value2 where condition:
respond to value2
case value3:
respond to value3
default:
otherwise,do something else
}
```
##### 具體`switch`的例子如下:
```
let point: ( x: Int , y: Int ) = ( 1 , 1 )
switch point {
case let ( x , y ) where x == y :
print("It is on the line x == y!")
print("The point is (\(x),\(y))")
case let ( x , y ) where x == -y :
print("It is on the line x == -y!")
print("The point is (\(x),\(y))")
case let ( x , y ):
print("It is just an ordinary point.")
print("The point is (\(x),\(y))")
}
```
> 在`case`后面使用匹配模式限定條件后再使用where進行限定。
##### `if case`
使用`if`語句簡化如下代碼:
```
switch age {
case 10...19:
print("You're a teenager")
default:
print("You're not a teenager")
}
// 使用if case簡化寫法
if case 10...19 = age {
print("You're a teenager")
}
// 使用if case簡化寫法,再加上where進行限定
if case 10...19 = age , age >= 18 {
print("You're a teenager abd in a college.")
}
// 再如
let vector = (4, 0)
if case (let x , 0) = vector , x > 2 && x < 5 {
print("It's the vector!")
}
```
> 注意使用 `,` 分割where限定條件
##### `for case`
求1 ... 100 以內被3整除的數
```
for i in 1...100 {
if i%3 == 0{
print(i)
}
}
// 使用 for case 簡寫
for case let i in 1...100 where i%3 == 0{
print(i)
}
```
拓展閱讀:[Pattern Matching, Part 4: if case, guard case, for case](http://alisoftware.github.io/swift/pattern-matching/2016/05/16/pattern-matching-4/)
#### `guard` 代碼風格
有一個函數,接收幾個參數,如下:
```
/**
* money 擁有的金錢
* price 價格
* capacity 容量
* volume 物體體積
* 用戶使用money購買價值price的物品,物品的體積是volume,然而用戶擁有的最大容量是capacity
*/
func buy(money: Int, price: Int, capacity: Int, volume: Int) {
if money >= price { // 是否有足夠的金錢
if capacity >= volume { // 是否有足夠的容量
print("I can buy it!")
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left.")
}else{
print("Not enough capactiy.") // 容量不夠
}
}else{
print("Not enough money.") // 金錢不夠
}
}
// 使用guard改寫代碼
func buyGuard(money: Int, price: Int, capacity: Int, volume: Int) {
guard money >= price else {
print("Not enough money.") // 金錢不夠
return
}
guard capacity >= volume else {
print("Not enough capactiy.") // 容量不夠
return
}
print("I can buy it!")
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left.")
}
```
> 使用`guard` 關鍵字將不符的條件全部排除,然后我們可以專注于自己的業務邏輯開發,使得代碼清晰。
- 學習筆記
- 基礎
- 基本類型之整型
- 基本類型之浮點型
- 基本類型之布爾類型以及簡單的 if 語句
- 基礎類型之元組
- 基本類型之其他
- 運算符
- 基礎運算符
- 比較運算符、邏輯運算符
- 三元運算符
- 范圍運算符for-in
- 邏輯控制
- 循環結構
- 選擇結構
- 字符串
- Character和Unicode
- String.index 和 range
- 可選型
- 容器類
- 數組初始化
- 數組基本操作
- 字典初始化
- 字典基本操作
- 集合初始化
- 集合基本操作
- 函數
- 閉包
- 枚舉
- 結構體
- 類
- 文檔注釋
- 屬性和方法
- 下標和運算符重載
- 拓展和泛型
- 協議
- 其他
- Swift 3.0 For 循環
- Swift 隨機數的生成
- IOS開發玩轉界面 UIKit
- UILable 文本顯示控件
- UIButton 簡單的交互控件
- UIImageView 圖片控件
- UISearchBar 搜索控件