美文网首页
swift5.3-day04--循环

swift5.3-day04--循环

作者: 江山此夜寒 | 来源:发表于2020-09-11 09:10 被阅读0次

1、for循环

let count = 1...10
for number in count {
    print("Number is \(number)")
}

对数组做同样的事情:

let albums = ["Red", "1989", "Reputation"]
for album in albums {
    print("\(album) is on Apple Music")
}

如果您不使用for循环赋予您的常量,则应改用下划线,这样Swift不会创建不必要的值:

for _ in 1...5 {
    print("play")
}

2、while循环

var number = 1
while number <= 20 {
    print(number)
    number += 1
}
print("Ready or not, here I come!")

3、repeat循环

repeat循环,它与while循环相同,只是要检查的条件最后出现

var number = 1

repeat {
    print(number)
    number += 1
} while number <= 20

print("Ready or not, here I come!")

条件在循环的末尾出现,因此repeat循环内的代码将始终至少执行一次,而while循环在首次运行之前会检查其条件。

4、退出循环

您可以随时使用break关键字退出循环

var countDown = 10

while countDown >= 0 {
    print(countDown)
    if countDown == 4 {
        print("I'm bored. Let's go now!")
        break
    }
    countDown -= 1
}

5、退出多个循环

在嵌套循环中,使用常规时break,仅会退出内部循环–外循环将在中断处继续。

如果我们想中途退出,我们需要做两件事。首先,我们给外部循环添加一个标签,如下所示:

其次,在内部循环中添加条件,然后使用break outerLoop来同时退出两个循环:

outerLoop: for i in 1...10 {
    for j in 1...10 {
        let product = i * j
        print ("\(i) * \(j) is \(product)")

        if product == 50 {
            print("It's a bullseye!")
            break outerLoop
        }
    }
}

6、跳过

break关键字退出循环。但是,如果您只想跳过当前项目并继续进行下一项,则应continue改用

for i in 1...10 {
    if i % 2 == 1 {
        continue
    }

    print(i)
}

7、无限循环

要进行无限循环,只需将其true用作您的条件。true始终为true,因此循环将永远重复。警告:请确保您有退出循环的检查,否则它将永远不会结束。

var counter = 0

while true {
    print(" ")
    counter += 1

    if counter == 273 {
        break
    }
}

相关文章

  • swift5.3-day04--循环

    1、for循环 对数组做同样的事情: 如果您不使用for循环赋予您的常量,则应改用下划线,这样Swift不会创建不...

  • python学习笔记(2)

    循环嵌套:在循环中嵌入其他的循环体,for循环中可以嵌入for循环,while循环中嵌入while循环,for循环...

  • 循环结构

    for循环 for in循环 while循环 do while循环

  • 《每天一点Java知识》Java基础知识——循环

    循环概念 循环是在一定条件下进行循环的逻辑结构 循环组成 循环由循环入口、循环条件与循环体组成。 循环分类 已知次...

  • 4-8 循环引用

    3种循环引用 自循环引用 相互循环引用 多循环引用 Block的循环引用 NSTimer 的循环引用 破除循环引用...

  • java 温故知新 第三天

    1.循环for循环 循环次数可知 最常用while循环 循环次数非必...

  • go逻辑判断语句

    if语句 for 循环 循环嵌套 for 死循环 for 循环的分解版

  • typescript笔记(四)

    一、循环:for循环、for...in...循环、for…of 、forEach、every 和 some 循环、...

  • while循环 for循环

    循环语句whilei=1while i<=20:if i%5==0:print(i)else:print(i,en...

  • 循环语句

    for循环 whil循环 dowhile循环

网友评论

      本文标题:swift5.3-day04--循环

      本文链接:https://www.haomeiwen.com/subject/wbrvektx.html