Swift #10:循环
发布: (2025年12月10日 GMT+8 05:54)
1 min read
原文: Dev.to
Source: Dev.to
while
while 验证一个条件,并在该条件变为 false 之前执行代码块。
var counter = 0
while counter in { ... }.
for‑in loop
for‑in 循环遍历集合中的元素。
let input = [1, 3, 5]
for value in input {
print(value * 2)
}
// Imprime 2, 6, 10
使用下划线当值不需要时
当 for‑in 循环中的常量不需要时,可以用下划线替代:
let input = [1, 3, 5]
for _ in input {
print("Hola")
}
// Imprime: "Hola", "Hola", "Hola"
where 子句
where 子句同样适用于 for‑in,用于仅执行满足特定条件的迭代。例如:
let input = [1, 3, 5, 6]
for value in input where value % 3 != 0 {
print(value * 2)
}
// Imprime 2, 10