swift篇 基础知识7--控制流(for-in,switch,while)

博客介绍了Swift中的For-in、switch和while循环。For-in循环涵盖数组、字典及数字范围的情况,数字范围循环可忽略值,还可使用函数跳过标记。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值