Swift #10:循环

发布: (2025年12月10日 GMT+8 05:54)
1 分钟阅读
原文: 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
Back to Blog

相关文章

阅读更多 »

Swift #12:函数

函数是由大括号 { 包围并以名称标识的代码块。不同于在循环和条件中使用的代码块……

Swift的来临

请提供您希望翻译的具体摘录或摘要文本,我才能为您进行简体中文翻译。

Swift #11:守卫语句

Guard 语句 guard 包含一个条件,随后是 else 和一个 guard 块。如果条件为 false,则执行 guard 块并…

从算法到冒险

《From Algorithms to Adventures》的封面图片 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-...