1. For in 循环
遍历一个集合中的所有元素。 例如:数组中的元素、范围内的数字或者字符串中的字符。
- 遍历一个数组所有元素:
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 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)") // 输出“3 to the power of 10 is 59049”
- 使用半开区间运算符(…<)来表示一个左闭右开的区间:
let minutes = 60
for tickMark in 0..<minutes {
// 每一分钟都渲染一个刻度线(60次)
}
- 可以每 5 分钟作为一个刻度。使用 stride(from:to:by:) 函数跳过不需要的标记:
let minuteInterval = 5
let minutes = 60
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// 每5分钟渲染一个刻度线(0, 5, 10, 15 ... 45, 50, 55)
}
- 在闭区间使用 stride(from:through:by:) 起到同样作用:
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// 每3小时渲染一个刻度线(3, 6, 9, 12)
}
2. While 循环
while 循环会一直运行一段语句直到条件变成 false。Swift 提供两种 while 循环形式:
- while 循环,每次在循环开始时计算条件是否符合。
- repeat-while 循环,每次在循环结束时计算条件是否符合。
2.1 While
- while 循环从计算一个条件开始。如果条件为 true,会重复运行一段语句,直到条件变为 false。
- while 循环的一般格式:
while condition {
statements
}
2.2 Repeat-While
- 判断循环条件之前,先执行一次循环的代码块。然后重复循