詳解Swift語言的while循環(huán)結構
Swift 編程語言中的 while 循環(huán)語句只要給定的條件為真時,重復執(zhí)行一個目標語句。
語法
Swift 編程語言的 while 循環(huán)的語法是:
while condition
{
statement(s)
}
這里 statement(s) 可以是單個語句或語句塊。condition 可以是任何表達式。循環(huán)迭代當條件(condition)是真的。 當條件為假,則程序控制進到緊接在循環(huán)之后的行。
數字0,字符串“0”和“”,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個真值 !或者 not 則返回一個特殊的假值。
流程圖
while循環(huán)在這里,關鍵的一點:循環(huán)可能永遠不會運行。當在測試條件和結果是假時,循環(huán)體將跳過while循環(huán),之后的第一個語句將被執(zhí)行。
示例
import Cocoa
var index = 10
while index < 20
{
println( "Value of index is \(index)")
index = index + 1
}
在這里,我們使用的是比較操作符 < 來比較 20 變量索引值。因此,盡管索引的值小于 20,while 循環(huán)繼續(xù)執(zhí)行的代碼塊的下一代碼,并疊加指數的值到 20, 這里退出循環(huán)。在執(zhí)行時,上面的代碼會產生以下結果:
Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19
do...while循環(huán)
不像 for 和 while 循環(huán),在循環(huán)頂部測試循環(huán)條件,do...while 循環(huán)檢查其狀態(tài)在循環(huán)的底部。
do... while循環(huán)類似于while循環(huán), 不同之處在于 do...while 循環(huán)保證執(zhí)行至少一次。
語法
在 Swift 編程語言中的 do...while 語法如下:
do
{
statement(s);
}while( condition );
應當指出的是,條件表達式出現(xiàn)在循環(huán)的底部,所以在測試條件之前循環(huán)語句執(zhí)行一次。如果條件為真,控制流跳回起來繼續(xù)執(zhí)行,循環(huán)語句再次執(zhí)行。重復這個過程,直到給定的條件為假。
數字 0,字符串 “0” 和 “” ,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個真值 !或者 not 則返回一個特殊的假值。
流程圖
實例
import Cocoa
var index = 10
do{
println( "Value of index is \(index)")
index = index + 1
}while index < 20
當執(zhí)行上面的代碼,它產生以下結果:
Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19
相關文章
Swift使用WKWebView在iOS應用中調用Web的方法詳解
這篇文章主要介紹了Swift使用WKWebView在iOS應用中調用Web的方法詳解,使用WKWebView便等于使用和Safari中相同的JavaScript解釋器,用來替代過去的UIWebView,需要的朋友可以參考下2016-04-04