swift學習筆記 --- Control Flow

這篇文章主要講 swift 和 C 語言不同的地方

 For-In Loops

    用這個便於遍歷數組,字典等
 

 Repeat-While

   相當於 C 裏的 do-While
 
 Switch
    1.當 Switch 中的值成功匹配了一個 case,不會繼續向下執行,它會直接跳出 switch
    2.每條 case 對應的可執行語句不能爲空
    3.一個case裏如果要匹配多個值,那麼這多個值必須一逗號隔開
    4.case裏的值可以是一個範圍值

        let c = 1

        switch c {

             case 0...9 : print("find 0~9")

             case 5: print("find 5")

             default:

             print("not find")

        }

   5.switch 可以匹配一個元組

   6.switch case 中要匹配的值可以是相同的

   7.switch 支持值綁定

               let c = 1

               switch c {

               case let x: print(x)

               case 5: print("find 5")

               default:

                     print("not find")

               }

                 case let x 可以匹配任何值,並把 c 的值賦給 x
        8. switch 能用 where 來添加額外的條件
                                 

               let c = 1

               switch c {

               case let x where x != 5 : print(x)

               case 5print("find 5")

               default:

                     print("not find")

               }

 continue 同 C
  
 fallthrough
                   用在 switch 中,使  語句能夠一直執行下去,造成跟 c 中 switch 一樣的效果

標記語句:
               這裏跟 java 很像,就是給一個循環或者 switch 語句前加個標籤方便 跳出或者跳入循環
               

       tag1: while true{

              print("tag1")

              tag2 : for(var i = 0 ; i <= 10; i++){

                      print("in for")

                      tag3:switch "4"{

                      case "c":

                      break tag1

                      default:

                       continue tag2

                }

            }

        }

 guard statement        
                guard statement 要求必須判斷條件爲真,且其必帶一個 else 分支,這個分支裏必須要有控制轉移語句,如 return、           
                  break、continue、throw 或者調用一個沒有返回值的函數

檢查 API 的可用性
                            

              if #available(platform name version, ..., *) {

                 statements to execute if the APIs are available

               } else {

               fallback statements to execute if the APIs are unavailable

               }

               例子:

               

              if #available(iOS 10, macOS 10.12, *) {

                // 執行這裏 iOS最低版本爲iOS 10 macOS 最低版本爲 10.12 

              } else {

               // Fall back to earlier iOS and macOS APIs

              }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章