For循環
For-In
我們可以使用for-in循環來遍歷一個集合裏的所有元素,例如由數字表示的區間、數組中的元素、字符串中的字符。
for index in 1...3{
print(index)
}
index是一個每次循環遍歷開始時被自動賦值的常量,這種情況下,index在使用前不需要聲明,只需要將它包含在循環的聲明中,
就可以對其進行隱式聲明。
let base = 3
let power = 3
var answer = 1
for _ in 1...power{
answer = base * answer
print(answer)
}
如果我們不需要知道區間內每一項的值,可以使用下劃線(_)替代變量名來忽略對值的訪問。
For條件遞增
for(var i=0;i<3;i++){
print(i)
}
for var i=0;i<3;++i {
print(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")
}
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
print("The letter A")
default:
print("Not the letter A")
}
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
fallthrough
case "A":
print("The letter A")
default:
print("Not 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).")
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")
}
在上面的例子中,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