1、for循環(huán)
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循環(huán)賦予您的常量,則應改用下劃線,這樣Swift不會創(chuàng)建不必要的值:
for _ in 1...5 {
print("play")
}
2、while循環(huán)
var number = 1
while number <= 20 {
print(number)
number += 1
}
print("Ready or not, here I come!")
3、repeat循環(huán)
repeat循環(huán),它與while循環(huán)相同,只是要檢查的條件最后出現
var number = 1
repeat {
print(number)
number += 1
} while number <= 20
print("Ready or not, here I come!")
條件在循環(huán)的末尾出現,因此repeat循環(huán)內的代碼將始終至少執(zhí)行一次,而while循環(huán)在首次運行之前會檢查其條件。
4、退出循環(huán)
您可以隨時使用break關鍵字退出循環(huán)
var countDown = 10
while countDown >= 0 {
print(countDown)
if countDown == 4 {
print("I'm bored. Let's go now!")
break
}
countDown -= 1
}
5、退出多個循環(huán)
在嵌套循環(huán)中,使用常規(guī)時break,僅會退出內部循環(huán)–外循環(huán)將在中斷處繼續(xù)。
如果我們想中途退出,我們需要做兩件事。首先,我們給外部循環(huán)添加一個標簽,如下所示:
其次,在內部循環(huán)中添加條件,然后使用break outerLoop來同時退出兩個循環(huán):
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關鍵字退出循環(huán)。但是,如果您只想跳過當前項目并繼續(xù)進行下一項,則應continue改用
for i in 1...10 {
if i % 2 == 1 {
continue
}
print(i)
}
7、無限循環(huán)
要進行無限循環(huán),只需將其true用作您的條件。true始終為true,因此循環(huán)將永遠重復。警告:請確保您有退出循環(huán)的檢查,否則它將永遠不會結束。
var counter = 0
while true {
print(" ")
counter += 1
if counter == 273 {
break
}
}