詳解Swift語言的while迴圈結構_Swift

來源:互聯網
上載者:User

Swift 程式設計語言中的 while 迴圈語句只要給定的條件為真時,重複執行一個目標語句。

文法
Swift 程式設計語言的 while 迴圈的文法是:

複製代碼 代碼如下:

while condition
{
   statement(s)
}

這裡 statement(s) 可以是單個語句或語句塊。condition 可以是任何錶達式。迴圈迭代當條件(condition)是真的。 當條件為假,則程式控制進到緊接在迴圈之後的行。

數字0,字串“0”和“”,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個真值 !或者 not 則返回一個特殊的假值。

流程圖

while迴圈在這裡,關鍵的一點:迴圈可能永遠不會運行。當在測試條件和結果是假時,迴圈體將跳過while迴圈,之後的第一個語句將被執行。

樣本

複製代碼 代碼如下:

import Cocoa
 
var index = 10

while index < 20
{
   println( "Value of index is \(index)")
   index = index + 1
}


在這裡,我們使用的是比較操作符 < 來比較 20 變數索引值。因此,儘管索引的值小於 20,while 迴圈繼續執行的代碼塊的下一代碼,併疊加指數的值到 20, 這裡退出迴圈。在執行時,上面的代碼會產生以下結果:

Value of index is 10Value of index is 11Value of index is 12Value of index is 13Value of index is 14Value of index is 15Value of index is 16Value of index is 17Value of index is 18Value of index is 19

do...while迴圈
不像 for 和 while 迴圈,在迴圈頂部測試迴圈條件,do...while 迴圈檢查其狀態在迴圈的底部。

do... while迴圈類似於while迴圈, 不同之處在於 do...while 迴圈保證執行至少一次。

文法
在 Swift 程式設計語言中的 do...while 文法如下:

複製代碼 代碼如下:

do
{
   statement(s);
}while( condition );

應當指出的是,條件運算式出現在迴圈的底部,所以在測試條件之前迴圈語句執行一次。如果條件為真,控制流程跳回起來繼續執行,迴圈語句再次執行。重複這個過程,直到給定的條件為假。

數字 0,字串 “0” 和 “” ,空列表 list(),和 undef 全是假的在布爾上下文中,除此外所有其他值都為 true。否定句一個真值 !或者 not 則返回一個特殊的假值。

流程圖

執行個體

複製代碼 代碼如下:

import Cocoa
 
var index = 10

do{
   println( "Value of index is \(index)")
   index = index + 1
}while index < 20


當執行上面的代碼,它產生以下結果:

Value of index is 10Value of index is 11Value of index is 12Value of index is 13Value of index is 14Value of index is 15Value of index is 16Value of index is 17Value of index is 18Value of index is 19

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.