swift5.3-day04--循环

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
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容