For-in循环
数组、字典的for-in循环我以前整理过,在这就不重复讲了,具体的请看
swift篇 基础知识6-集合类型【数组(Array)、字典(Dictionary)】
数字范围的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
//闭区间 1...<5
范围[1,2,3,4]
如果你不需要区间序列内每一项的值,你可以使用下划线(_
)替代变量名来忽略这个值:
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”
使用 stride(from:to:by:)
函数跳过不需要的标记。
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// 每5分钟渲染一个刻度线(0, 5, 10, 15 ... 45, 50, 55)
}
使用 stride(from:to:by:)
和使用 stride(from:through:by:)的区别,以上例子解释:前者范围[0,60)不包括minutes,后者范围[0,60]包括minutes
switch 循环
let time = 5
var message = ""
switch time {
case 7:
message = "起床时间"
case 8,12,18:
message = "吃饭时间"
case let x where x>18 && x<=24: //表示:19至24点
message = "happy 时间"
case 1...6: //表示:1至6点(包括6点)
message = "休息时间"
default:
message = "忙碌时间"
}
while循环
var i = 1
while i<=5 {
i += 1
}
print(i)
// i+= 1 执行了5次
//i最后的值为 6
var j = 1
repeat
{
j += 1
}while j <= 5
print(j)
//j += 1 执行了5次
//j最后的值为6