在开发中经常会需要循环,常见的循环有: for / while / do 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 = 10
while a > 0 {
a--
}
/* 错误写法
while (a) {
a--
}
*/
- do while循环
- 使用repeat关键字来代替了do
let b = 0
repeat {
print(b)
b++
} while b < 20
- 系列文章