Swift学习(四:控制流)

作者: 爱偷懒的万万 | 来源:发表于2016-07-15 14:43 被阅读38次
    1. For- In循环
        for index in 1...5{
                print (index)
        }
    

    注意:index是一个每次循环遍历开始时被自动赋值的常量。这种情况下不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用let关键字声明。

    • 如果不需要知道每一项的值,可以使用_代替变量名来忽略对值的访问。

        for _ in 1...10{
                print("haha")
        }
      
    • 遍历数组

        let names = ["aa","ss","dd"]
        for name in names {
                print("hello\(name)")
        }
      
    • 遍历字典

        let dic = ["aa" : "AA", "ss" : "SS","dd" :"DD"]
        for (key,value) in dic{
                print("\(key) : \(value)")
        }
      
    2.While循环
    • while循环,每次在循环开始时计算条件是否符合

        while condition {  
            statements
        }
      
    • repeat-while循环,每次在循环结束时计算条件是否符合

        repeat {
            statements
        } while condition
    
    3. 条件语句
        var a = 10
        if a <=11{
              print("haha")    
        }else if{
              print("...")
        }                               //haha
    
    4.Switch

    每一个 case 都是代码执行的一条分支,这与if语句类似。与之不同的是,switch语句会决定哪一条分支应该被执行。
    switch语句必须是完备的。这就是说,每一个可能的值都必须至少有一个case分支与之对应。在某些不可能涵盖所有值的情况下,你可以使用默认(default)分支满足该要求,这个默认分支必须在switch语句的最后面。

        let index : Character = "e"
        switch index {
                case "a","b","c":
                    print("hehe")
                case "s","d","f":
                      print("haha")
                default:
                        print("\(index)")
        }
    

    注意:*在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。这使得switch语句更安全、更易用,也避免了因忘记写break语句而产生的错误。
    每一个 case 分支都必须包含至少一条语句

    • 一个 case 也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):

       switch index {
               case value1,
                       value2:
                             statements
       }
      
    • 区间匹配

        let a = 20
        var c : String
        switch a {
                case 0 :
                      c = "no"
                case 1..<5:
                      c = "a few"
                case 5..<10:
                      c = "several"
                default:
                      c = "many"
        }
      
        print("\(c)")          //many
      
    • 元组

        let a = (1,1)
        switch a {
                case(0,0):
                        print("1")
                case( _ , 0 ):
                        print("2")
                case( 0 , _):
                          print("3")
                case(-2...2,-2...2):
                          pint("4")
        }                                      //4
      

    下面的例子展示了如何在一个(Int, Int)类型的元组中使用值绑定来分类下图中的点(x, y):

        let anotherPoint = (2, 0)
        switch anotherPoint {
            case (let x, 0):
                print("on the x-axis with an x value of \(x)")
            case (0, let y):
                  print("on the y-axis with a y value of \(y)")
            case let (x, y):
                  print("somewhere else at (\(x), \(y))")
            }
            // 输出 "on the x-axis with an x value of 2"
    
    • where
      case 分支的模式可以使用where语句来判断额外的条件

        let yetAnotherPoint = (1, -1)
        switch yetAnotherPoint {
        case let (x, y) where x == y:
            print("(\(x), \(y)) is on the line x == y")
        case let (x, y) where x == -y:
            print("(\(x), \(y)) is on the line x == -y")
        case let (x, y):
            print("(\(x), \(y)) is just some arbitrary point")
        }
        // 输出 "(1, -1) is on the line x == -y"
      
    5.控制转移语句

    swift有5种控制转移语句:continue,break,fallthrough,return,throw

    • Continue
      continue语句告诉循环体停止本次循环,重新开始下一次循环,而不是终止整个循环。

        let input = "great minds think alike"
        var b = " "
        for c in input.characters {
            switch c {
            case "a","e","i","o","u"," ":
                continue
            default:
                b.append(c)
            }
        }
        print(b)
      
    • Break
      立刻结束整个控制流的执行

        let numberSymbol: Character = "三"  // 简体中文里的数字 3
        var possibleIntegerValue: Int?
         switch numberSymbol {
        case "1", "١", "一", "๑":
            possibleIntegerValue = 1
        case "2", "٢", "二", "๒":
            possibleIntegerValue = 2
        case "3", "٣", "三", "๓":
            possibleIntegerValue = 3
        case "4", "٤", "四", "๔":
            possibleIntegerValue = 4
        default:
            break
        }
        if let integerValue = possibleIntegerValue {
            print("The integer value of \          (numberSymbol) is \(integerValue).")
        } else {
        print("An integer value could not be found for \(numberSymbol).")
        }
        // 输出 "The integer value of 三 is 3."
      
    • 贯穿 Fallthrough

    Swift 中的switch不会从上一个case分支落入到下一个 case分支中。相反,只要第一个匹配到的 case分支完成了它需要执行的语句,整个switch代码块完成了它的执行。相比之下,C 语言要求你显式地插入break语句到每个switch分支的末尾来阻止自动落入到下一个 case分支中。Swift 的这种避免默认落入到下一个分支中的特性意味着它的switch 功能要比 C 语言的更加清晰和可预测,可以避免无意识地执行多个case分支从而引发的错误。
    如果你确实需要 C 风格的贯穿的特性,你可以在每个需要该特性的case 分支中使用fallthrough关键字。下面的例子使用fallthrough来创建一个数字的描述语句。

        let integerToDescribe = 5
        var description = "The number \(integerToDescribe) is"
        switch integerToDescribe {
        case 2, 3, 5, 7, 11, 13, 17, 19:
            description += " a prime number, and   also"
            fallthrough
        default:
            description += " an integer."
        }
        print(description)
        // 输出 "The number 5 is a prime number, and also an integer."
    
    • 提前退出 guard

      a = 7
      guard a >= 10 else { return }
      //return

    • 检测API可用性

        if #available(iOS 9, OSX 10.10, *) {
            // 在 iOS 使用 iOS 9 的 API, 在 OS X 使用 OS X v10.10 的 API
        } else {
            // 使用先前版本的 iOS 和 OS X 的 API
        }
      

    相关文章

      网友评论

      • ddf82c5e7477:1. for循环在swift2.2和3.0分别如何取下标?
        2. switch写的太简单了,去swiftGG看switch匹配模式

      本文标题:Swift学习(四:控制流)

      本文链接:https://www.haomeiwen.com/subject/ustyjttx.html