循環的介紹
- 在開發中經常會需要循環
- 常見的循環有:for/while/do while.
- 這裏我們只介紹for/while,因爲for/while最常見
for循環的寫法
- 最常規寫法
// 傳統寫法
for var i = 0; i < 10; i++ {
print(i)
}
- 區間for循環
for i in 0..<10 {
print(i)
}
for i in 0...10 {
print(i)
}
- 特殊寫法
- 如果在for循環中不需要用到下標i
for _ in 0..<10 {
print("hello")
}
while和do while循環
- while循環
- while的判斷句必須有正確的真假,沒有非0即真
- while後面的()可以省略
var a = 0
while a < 10 {
a++
}
- do while循環
- 使用repeat關鍵字來代替了do
let b = 0
repeat {
print(b)
b++
} while b < 20