今天要來看的是控制流(Control Flow)這個東西,裡面有很多語法,有 while循環可以多次執行動作,if、guard 還有 switch 可以根據條件來設定要用哪一個方法。
還有 for-in 循環,可以讓你方便遍歷。
可以使用 for-in 遍歷集合類型的項,數字範圍或字元串中的字元。
Array 遍歷
let names =["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
字典 遍歷
let numberOfLegs =["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs
也可以用 for-in 設一個循環的數字範圍。
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
也可以用變數常數取代設的值。
let base=3
let power=10
var answer=1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// Prints "3 to the power of 10 is 59049"
範圍的部分有兩種方法設定。
stride(from:to:by:)跟stride(from:through:by:)
後者可以代替封閉範圍
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
}
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
let hours=12
let hourInterval=3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// render the tick mark every 3 hours (3, 6, 9, 12)
}
今天就先介紹到這裡,明天再繼續 while 的控制流。