Swift編程基礎(四):控制流

For循環

For-In

我們可以使用for-in循環來遍歷一個集合裏的所有元素,例如由數字表示的區間、數組中的元素、字符串中的字符。                                          
for index in 1...3{
     print(index)
}
//1
//2
//3
index是一個每次循環遍歷開始時被自動賦值的常量,這種情況下,index在使用前不需要聲明,只需要將它包含在循環的聲明中,
就可以對其進行隱式聲明。
let base = 3
let power = 3
var answer = 1
for _ in 1...power{
answer = base * answer
   print(answer)
}
//3
//9
//27
如果我們不需要知道區間內每一項的值,可以使用下劃線(_)替代變量名來忽略對值的訪問。

For條件遞增

//格式一:
for(var i=0;i<3;i++){
    print(i)
}

//格式二:
for var i=0;i<3;++i {
    print(i)
}
//備註:格式二中的++i不能寫成i++,否則報錯。如果想寫成i++,就用格式一。

Switch

Swift裏面的switch與OC中的語句不同。在Swift中,當匹配的case分支中的代碼執行完畢後,程序會終止switch語句,
而不會繼續執行下一個case分支。也就是說,不需要在case分支中顯示得使用break語句。
既然Swift裏面的switch語句有這樣的特性,那麼如果想要達到貫穿執行怎麼辦呢?使用***fallthrough***關鍵字;
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l","m","n", "p", "q", "r", "s", "t", "v", "w", "x", "y","z":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) is not a vowel or a consonant")
} 
//輸出:e is a vowel 
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
     print("The letter A")
default:
     print("Not the letter A")
}
//這麼寫,在OC裏對,在Swift裏報錯
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
    fallthrough
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
//好吧,加上貫穿關鍵字:fallthrough,輸出:The letter A

Switch的區間匹配

let count = 30
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
     naturalCount = "no"
case 1...9:
     naturalCount = "a few"
case 10...99:
     naturalCount = "tens of"
case 100...999:
     naturalCount = "hundreds of"
default:
     naturalCount = "thousands and millions of"
}
print("There are \(naturalCount) \(countedThings).")
//輸出:There are tens of stars in the Milky Way.

Switch與元組

元組中下劃線(_)可以用來匹配所有可能的值
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
     print("(0, 0) is at the origin")
case (_, 0):
     print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
     print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
     print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
     print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
//輸出:(1, 1) is inside the box
在上面的例子中,switch語句會判斷某個點是否是原點(0,0),是否在想軸上,是否在Y軸上,是否在一個以原點爲中心的4*4
的矩形裏,或者在這個矩形外面。
不像OC語言,Swift允許多個case匹配同一個值。也就是說,點(0,0)其實可以匹配前四個case,但是首先匹配case(0,0),
因此剩下的能夠匹配的case分支都會被忽略掉。

Switch的值綁定

case分支的模式允許將匹配的值綁定到一個臨時的變量或常量,這些常量或變量在該case分支裏就可以被引用了
——這種行爲被稱爲值綁定。
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))")
}
//輸出:on the x-axis with an x value of 2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章