Swift While和Repeat While循環
當迭代次數未知時,While和Repeat while循環被用作for-in循環的替代方案。愛掏網 - it200.comWhile循環執行一組語句,直到條件為假為止。愛掏網 - it200.com這種循環通常在你不知道迭代次數時使用。愛掏網 - it200.com
在Swift中有兩種類型的循環:
- While循環
- Repeat While循環
Swift的While循環在每次執行時都會評估其條件。愛掏網 - it200.com
語法
while (TestExpression) {
// statements
}
在這里,TestExpression是一個布爾表達式。愛掏網 - it200.com如果它為真,則執行while循環中的語句。愛掏網 - it200.com
- 在while循環中,語句將被執行。愛掏網 - it200.com
- 然后,TestExpression將再次進行評估。愛掏網 - it200.com
這個過程會一直進行,直到TestExpression為假為止。愛掏網 - it200.com當TestExpression得到假條件時,while循環終止。愛掏網 - it200.com
While循環的流程圖
示例
var currentLevel:Int = 0, finalLevel:Int = 6
let gameCompleted = true
while (currentLevel <= finalLevel) {
//play game
if gameCompleted {
print("You have successfully completed level \(currentLevel)")
currentLevel += 1
}
}
//outside of while loop
print("Terminated! You are out of the game ")
輸出:
You have successfully completed level 0
You have successfully completed level 1
You have successfully completed level 2
You have successfully completed level 3
You have successfully completed level 4
You have successfully completed level 5
You have successfully completed level 6
Terminated! You are out of the game
在上面的程序中,while循環執行直到條件被評估為false,并且一旦獲得false條件,它就終止。愛掏網 - it200.com
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。