2015年8月10日 星期一

【Swift 筆記 Draft】第 4 講: Flow Control 流程控制


循環 loop 語句:

1. for-in
2. for-condition-increment
3. while
4. do ... while

分支語句:

5. if condition
6. switch

跳轉語句:

7. fallthrough
8. where clause
9. break, continue
10. 可跳轉的標籤


for-in:

for index in 1 ... 10 { ...}

for _ in 1 ... 10 { ... } //當 index 在 { ... } 不被使用時
let nums = [1, 2, 3, 4, 5] for num in nums { ... } let dict1 = ["key1":1,"key2":2 ] for (key,value) in dict1 { ... } for character in "hello, world" { ... } for-condition-increment:

for initialization; condition; increment { ... }
while

while condition { ... }
do ... while

do { ... } while condition
無限循環:

for ; ; { ... }
while true { ... }
do { ... } while true
if condition

if condition { ...}

if condition { ...} else { ... }

if condition1 { ... }
else if condition2 { ... }
else { ... }
switch 可用於 Integer / Floating Point / Character / String / Tuple 等類型的數據做比較。

switch condition {
   case value1:
      statement1
   case value2, value3:
      statement2
   ...
   default:
      statementN+1
}
例如:範圍 range 比較: let weight = 80 switch weight { case 0 ..< 50: println("lower than standard") case 50: println("perfect") case 51 ... 200: println("above the standard) default: println("Not applicable") } where clause where: 在 case 中增加篩選條件 let weight = 80 switch weight { case let (x) where x < 50: println("lower than standard") case let (x) where x == 50: println("perfect") case let (x) where x > 50: println("above the standard") default: println("Not applicable") } 將 weight 這值 binding 到一個臨時的 constant / variable。(例如:x) fallthrough: fallthrough 為貫穿 case 而設計。例如: var n = 1 var x = 2 switch x { case 1: n++ case 2: n++ fallthrough case 3: n++ default: n++ } println("n = \(n)") //此時 n = 3 break, continue continue: 結束本次loop,進入下一個 loop break: 結束當前 statements 執行 可跳轉的標籤Label: forLabel:for index1 in 1 ... 5 { for index2 in 1 ... 5 { ... break forLabel } }

沒有留言:

張貼留言

prettyPrint();