詳解Swift語(yǔ)言的while循環(huán)結(jié)構(gòu)
Swift 編程語(yǔ)言中的 while 循環(huán)語(yǔ)句只要給定的條件為真時(shí),重復(fù)執(zhí)行一個(gè)目標(biāo)語(yǔ)句。
語(yǔ)法
Swift 編程語(yǔ)言的 while 循環(huán)的語(yǔ)法是:
while condition
{
statement(s)
}
這里 statement(s) 可以是單個(gè)語(yǔ)句或語(yǔ)句塊。condition 可以是任何表達(dá)式。循環(huán)迭代當(dāng)條件(condition)是真的。 當(dāng)條件為假,則程序控制進(jìn)到緊接在循環(huán)之后的行。
數(shù)字0,字符串“0”和“”,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個(gè)真值 !或者 not 則返回一個(gè)特殊的假值。
流程圖

while循環(huán)在這里,關(guān)鍵的一點(diǎn):循環(huán)可能永遠(yuǎn)不會(huì)運(yùn)行。當(dāng)在測(cè)試條件和結(jié)果是假時(shí),循環(huán)體將跳過(guò)while循環(huán),之后的第一個(gè)語(yǔ)句將被執(zhí)行。
示例
import Cocoa
var index = 10
while index < 20
{
println( "Value of index is \(index)")
index = index + 1
}
在這里,我們使用的是比較操作符 < 來(lái)比較 20 變量索引值。因此,盡管索引的值小于 20,while 循環(huán)繼續(xù)執(zhí)行的代碼塊的下一代碼,并疊加指數(shù)的值到 20, 這里退出循環(huán)。在執(zhí)行時(shí),上面的代碼會(huì)產(chǎn)生以下結(jié)果:
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)頂部測(cè)試循環(huán)條件,do...while 循環(huán)檢查其狀態(tài)在循環(huán)的底部。
do... while循環(huán)類(lèi)似于while循環(huán), 不同之處在于 do...while 循環(huán)保證執(zhí)行至少一次。
語(yǔ)法
在 Swift 編程語(yǔ)言中的 do...while 語(yǔ)法如下:
do
{
statement(s);
}while( condition );
應(yīng)當(dāng)指出的是,條件表達(dá)式出現(xiàn)在循環(huán)的底部,所以在測(cè)試條件之前循環(huán)語(yǔ)句執(zhí)行一次。如果條件為真,控制流跳回起來(lái)繼續(xù)執(zhí)行,循環(huán)語(yǔ)句再次執(zhí)行。重復(fù)這個(gè)過(guò)程,直到給定的條件為假。
數(shù)字 0,字符串 “0” 和 “” ,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個(gè)真值 !或者 not 則返回一個(gè)特殊的假值。
流程圖

實(shí)例
import Cocoa
var index = 10
do{
println( "Value of index is \(index)")
index = index + 1
}while index < 20
當(dāng)執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果:
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
相關(guān)文章
淺談在Swift中關(guān)于函數(shù)指針的實(shí)現(xiàn)
這篇文章主要介紹了淺談在Swift中關(guān)于函數(shù)指針的實(shí)現(xiàn),是作者根據(jù)C語(yǔ)言的指針特性在Swifft中做出的一個(gè)實(shí)驗(yàn),需要的朋友可以參考下2015-07-07
Swift用final關(guān)鍵字來(lái)防止重寫(xiě)
final關(guān)鍵字在大多數(shù)的編程語(yǔ)言中都存在,表示不允許對(duì)其修飾的內(nèi)容進(jìn)行繼承或者重新操作。下面通過(guò)實(shí)例代碼給大家介紹swift用final關(guān)鍵字來(lái)防止重寫(xiě)2016-12-12
Swift算法實(shí)現(xiàn)字符串轉(zhuǎn)數(shù)字的方法示例
最近學(xué)完了swift想著實(shí)踐下,就通過(guò)一些簡(jiǎn)單的算法進(jìn)行學(xué)習(xí)研究,下面這篇文章主要介紹了Swift算法實(shí)現(xiàn)字符串轉(zhuǎn)數(shù)字的方法,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-03-03
Swift使用transform 實(shí)現(xiàn)重復(fù)平移動(dòng)畫(huà)效果
這篇文章主要介紹了Swift使用transform 實(shí)現(xiàn)重復(fù)平移動(dòng)畫(huà)效果,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-07-07
swift中c風(fēng)格的for循環(huán)執(zhí)行效率
這篇文章主要介紹了swift中c風(fēng)格的for循環(huán)執(zhí)行效率 的相關(guān)資料,需要的朋友可以參考下2016-07-07

