循環 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 index in 1 ..< 10 { ...} for _ in 1 ... 10 { ... } //當 index 在 { ... } 不被使用時
for variable in range (範圍) // 範圍為整數值
for 變數 in range (範圍開始,範圍結束)
for 變數 in range (範圍開始,範圍結束,每次相差)
for 變數 in 矩陣Array
for 變數 in 字串
Example:
for x in range(5)
print x // 列印: 0,1,2,3,4
for x in range(1,5)
print x // 列印: 1,2,3,4
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 { ... }
whilewhile condition { ... }
do ... whiledo { ... } while condition
無限循環:for ; ; { ... } while true { ... } do { ... } while true
if conditionif condition { ...} if condition { ...} else { ... } if condition1 { ... } else if condition2 { ... } else { ... }
switch 可用於 Integer / Floating Point / Character / String / Tuple 等類型的數據做比較。 switch 必須涵蓋所有可能狀況,所以 default 不能省。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
2015年8月11日 星期二
【Swift 筆記 Draft】第 4 講: Flow Control 流程控制
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言