Welcome to Swift (蘋果官方Swift文檔初譯與註解二十八)---199~208頁(第四章-- 流程式控制制)

來源:互聯網
上載者:User

標籤:style   使用   strong   for   io   代碼   

Value Bindings (綁定值)

  在switch的case中可以綁定一個或者多個值給case體中的臨時常量或者變數,這個成為綁定值.

  代碼範例:

    let anotherPoint = (2, 0)

    switch anotherPoint {

    case (let x, 0):

        println("on the x-axis with an x value of \(x)")

    case (0, let y):

        println("on the y-axis with a y value of \(y)")

    case let (x, y):

        println("somewhere else at (\(x), \(y))")

    }

    // prints "on the x-axis with an x value of 2”

       

  這個switch語句判斷點是否在x-軸,在Y軸,或者其他地方.

  三個case語句中都定義了常量x和y,它們臨時的接收元組anotherPoint中的一個或者兩個值.第一個case中,”case (let x, 0)匹配任何一個Y值是0的點,並且賦值這個點的x值給臨時常  量x,同樣的,第二個case中,case (0, let y)匹配任意x值為0的點,並賦值這個點的y值給臨時常量y.

  一旦臨時常量被定義,它們就可以在case代碼塊中使用.

  注意,這個switch語句沒有預設的default case.最後的case, case let (x, y)定義了一個元組,它匹配其餘值的所有情況,因此在swithc語句最終不要要個default case.

  在上面的代碼例子中,x和y是通過使用關鍵字let定義的常量,因為不需要在case代碼塊中修改它們的值,但是它們也可以使用var關鍵字定義為變數.如果這樣做的話,一個臨時變數將會  被建立並且初始化相應的值.這個變數的任何改變都局限在case的代碼體中.

Where

  一個switch case可以使用where 檢查附加條件:

    let yetAnotherPoint = (1, -1)

    switch yetAnotherPoint {

    case let (x, y) where x == y:

        println("(\(x), \(y)) is on the line x == y")

    case let (x, y) where x == -y:

         println("(\(x), \(y)) is on the line x == -y")

    case let (x, y):

        println("(\(x), \(y)) is just some arbitrary point")

    }

    // prints "(1, -1) is on the line x == -y”

          

  這個switch語句判斷點是否在綠色的線(where x == y),是否在紫色的線(where x == -y),或者其他.

Control Transfer Statements (控制跳躍陳述式)

  控制跳躍陳述式會改變代碼執行的順序,代碼從一個地方跳至另一個地方.在Swift中有四種控制跳躍陳述式:

    continue

    break

    fallthrough

    return

  這裡會先講述control, break 和 fallthrough語句,return將在函數的部分說明.

Continue

  continue語句會告訴迴圈停止本次進行中的迴圈,並開始下一次迴圈,它一直沒有離開迴圈.

  注意點:

  在for-condition-increment迴圈中,調用continue語句後,仍會執行incermen的計算.迴圈本身仍會繼續執行,只是這次迴圈中的代碼被忽略了.

  下面的代碼例子示範了從一個小寫字串中移除所有母音和空格來建立一個加密的短句:

    let puzzleInput = "great minds think alike"

    var puzzleOutput = ""

    for character in puzzleInput {

        switch character {

         case "a", "e", "i", "o", "u", " ":

            continue

        default:

            puzzleOutput += character

        }

    }

    println(puzzleOutput)

    // prints "grtmndsthnklk”

  上面的代碼中,調用continue關鍵字,當匹配到一個母音或空格,就會結束本次迴圈並開始下一次遍曆迴圈.這樣可以確保switch代碼塊僅匹配(或忽略)母音和空格.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.