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

              }


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