美文网首页Swift
Swift4 基础部分:Control Flow

Swift4 基础部分:Control Flow

作者: Arnold134777 | 来源:发表于2017-07-20 22:34 被阅读96次

    本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

    系列文章:

    While

    Repeat-While

    The repeat-while loop in Swift is analogous to a do-while 
    loop in other languages.
    
    • Swift中repeat-while的逻辑类似其他语言中do-while,也是搞不懂Swift为什么要自己写一套。

    例子:

    repeat{
        print("invoked");
    }while(false);
    

    执行结果:

    invoked
    

    Switch

    In its simplest form, a switch statement compares a value
    against one or more values of the same type.
    
    • Switch中的一个case语句可以写入一个或者多个同类型的值。

    例子:

    func distinguishNumber(number: Int){
        switch number{
            case 2, 4, 6:
                print("\(number) is even");
            case 1, 3, 5:
                print("\(number) is odd");
            default:
                print("\(number) is exceed");
        }
    }
    distinguishNumber(number: 2);
    distinguishNumber(number: 3);
    distinguishNumber(number: 8);
    

    执行结果:

    2 is even
    3 is odd
    8 is exceed
    

    不存在隐式穿透(No Implicit Fallthrough)

    In contrast with switch statements in C and Objective-C, 
    switch statements in Swift do not fall through the bottom 
    of each case and into the next one by default. Instead, 
    the entire switch statement finishes its execution as soon 
    as the first matching switch case is completed, without 
    requiring an explicit break statement. This makes the 
    switch statement safer and easier to use than the one in C 
    and avoids executing more than one switch case by mistake.
    
    • Swift与OC,C中关于Swich中存在差异,Swift中默认匹配到执行的case,执行完成直接break,而其他的语言OC,C必须加入显式的break才能跳出。

    例子直接参考上述的例子即可。

    Interval Matching(间隔匹配)

    Values in switch cases can be checked for their inclusion in an 
    interval
    
    • Swich case中的匹配值可以是区间类型数据。

    例子:

    
    func distinguishNumber(number: Int){
        switch number{
            case 1...10:
                print("\(number) <= 10");
            case 10...Int.max:
                print("\(number) > 10");
            default:
                print("\(number) is exceed");
        }
    }
    distinguishNumber(number: 2);
    distinguishNumber(number: 13);
    

    执行结果:

    2 <= 10
    13 > 10
    

    Tuples

    You can use tuples to test multiple values in the same 
    switch statement. Each element of the tuple can be tested 
    against a different value or interval of values. 
    Alternatively, use the underscore character (_), also 
    known as the wildcard pattern, to match any possible 
    value.
    
    • Swich case中也可以使用元组,元组中的值也可以是区间类型数据。

    例子:

    func distinguishPostion(x: Int,y :Int){
        let somePoint = (x, y)
        switch somePoint {
        case (0, 0):
            print("\(somePoint) is at the origin")
        case (_, 0):
            print("\(somePoint) is on the x-axis")
        case (0, _):
            print("\(somePoint) is on the y-axis")
        case (-2...2, -2...2):
            print("\(somePoint) is inside the box")
        default:
            print("\(somePoint) is outside of the box")
        }
    }
    
    distinguishPostion(x: 0, y: 0);
    distinguishPostion(x: 1, y: 1);
    

    执行结果:

    (0, 0) is at the origin
    (1, 1) is inside the box
    

    Value Bindings

    A switch case can name the value or values it matches to 
    temporary constants or variables, for use in the body of 
    the case. This behavior is known as value binding, because 
    the values are bound to temporary constants or variables 
    within the case’s body.
    
    • Switch case中可以写入临时的变量绑定传入的值。

    例子:

    func distinguishPostion(x: Int,y :Int){
        let somePoint = (x, y)
        switch somePoint {
        case (0, 0):
            print("\(somePoint) is at the origin")
        case (let tempX, 0):
            print("\(somePoint) is on the x-axis,and x is \(tempX)")
        case (0, let tempY):
            print("\(somePoint) is on the y-axis,and y is \(tempY)")
        case (-2...2, -2...2):
            print("\(somePoint) is inside the box")
        default:
            print("\(somePoint) is outside of the box")
        }
    }
    
    distinguishPostion(x: 1, y: 0);
    distinguishPostion(x: 0, y: 1);
    

    执行结果:

    (1, 0) is on the x-axis,and x is 1
    (0, 1) is on the y-axis,and y is 1
    

    Where

    A switch case can use a where clause to check for additional 
    conditions.
    
    • Switch case中可以使用where 语句去做额外的条件判断。

    例子:

    
    func distinguishPostion(x: Int,y :Int){
        let somePoint = (x, y)
        switch somePoint {
        case let (x, y) where x == y:
            print("\(somePoint) is on the line x == y")
        case let (x, y) where x == -y:
            print("\(somePoint) is on the line x == -y")
        case let (x, y):
            print("\(somePoint) is just some arbitrary point")
        }
    }
    
    distinguishPostion(x: 0, y: 0);
    distinguishPostion(x: 1, y: -1);
    distinguishPostion(x: 0, y: 1);
    

    执行结果:

    (0, 0) is on the line x == y
    (1, -1) is on the line x == -y
    (0, 1) is just some arbitrary point
    

    Control Transfer Statements(控制转移状态)

    Control transfer statements change the order in which your 
    code is executed, by transferring control from one piece 
    of code to another. Swift has five control transfer 
    statements:
    
    continue
    break
    fallthrough
    return
    throw 
    
    • Swift中存在5种控制转移状态,即以上的5种。

    我们重点了解fallthrough,throw的使用。

    Fallthrough

    In Swift, switch statements don’t fall through the bottom 
    of each case and into the next one. That is, the entire 
    switch statement completes its execution as soon as the 
    first matching case is completed. By contrast, C requires 
    you to insert an explicit break statement at the end of 
    every switch case to prevent fallthrough. Avoiding default 
    fallthrough means that Swift switch statements are much 
    more concise and predictable than their counterparts in C, 
    and thus they avoid executing multiple switch cases by 
    mistake.
    
    If you need C-style fallthrough behavior, you can opt in 
    to this behavior on a case-by-case basis with the 
    fallthrough keyword. The example below uses fallthrough to 
    create a textual description of a number.
    
    
    • Switch case如果需要能当首个case执行完能执行到第二个case中必须加入Fallthrough关键字。

    例子:

    func distinguishPostion(x: Int,y :Int){
        let somePoint = (x, y)
        switch somePoint {
        case let (x, y) where x == y:
            print("\(somePoint) is on the line x == y")
            fallthrough;
        case let (_, 1):
            print("\(somePoint) is on the line y == 1")
        case let (x, y):
            print("\(somePoint) is just some arbitrary point")
        }
    }
    
    distinguishPostion(x: 1, y: 1);
    distinguishPostion(x: 1, y: -1);
    distinguishPostion(x: 0, y: 1);
    

    执行结果:

    (1, 1) is on the line x == y
    (1, 1) is on the line y == 1
    (1, -1) is just some arbitrary point
    (0, 1) is on the line y == 1
    
    The fallthrough keyword does not check the case conditions 
    for the switch case that it causes execution to fall into. 
    The fallthrough keyword simply causes code execution to 
    move directly to the statements inside the next case (or 
    default case) block, as in C’s standard switch statement 
    behavior.
    
    • fallthrough的关键字不会去检查case中的条件判断,写了条件判断也无效。

    例子:上述例子我们执行distinguishPostion(x: 1, y: 2);结果不变。

    标记语言(Labeled Statements)

    In Swift, you can nest loops and conditional statements 
    inside other loops and conditional statements to create 
    complex control flow structures. However, loops and 
    conditional statements can both use the break statement to 
    end their execution prematurely. Therefore, it is 
    sometimes useful to be explicit about which loop or 
    conditional statement you want a break statement to 
    terminate. Similarly, if you have multiple nested loops, 
    it can be useful to be explicit about which loop the 
    continue statement should affect.
    
    To achieve these aims, you can mark a loop statement or 
    conditional statement with a statement label. With a 
    conditional statement, you can use a statement label with 
    the break statement to end the execution of the labeled 
    statement. With a loop statement, you can use a statement 
    label with the break or continue statement to end or 
    continue the execution of the labeled statement.
    
    • Swift 中标记语言这里说的很明白,就是多层循环中可以利用标记结合break,continue达到很方便结束标记的某个循环逻辑。

    例子:

    let xLimitNum :Int = 20;
    let yLimitNum :Int = 6;
    var xSum :Int = 0;
    var ySum :Int = 0;
    
    xLoop:for x in 1...4{
        ySum = 0;
        yLoop:for y in 1...4{
            
            if ySum + y > yLimitNum{
                print("ySum:\(xSum) + y:\(y) > \(yLimitNum) break yLoop");
                break yLoop;
            }
            
            if xSum + y > xLimitNum{
                print("xSum:\(xSum) + y:\(y) > \(xLimitNum) break xLoop");
                break xLoop;
            }
            
            ySum += y;
            xSum += y;
            print("xSum:\(xSum - y) + y:\(y) = \(xSum)");
            print("ySum:\(ySum - y) + y:\(y) = \(ySum)");
        }
    }
    

    执行结果:

    xSum:0 + y:1 = 1
    ySum:0 + y:1 = 1
    xSum:1 + y:2 = 3
    ySum:1 + y:2 = 3
    xSum:3 + y:3 = 6
    ySum:3 + y:3 = 6
    ySum:6 + y:4 > 6 break yLoop
    xSum:6 + y:1 = 7
    ySum:0 + y:1 = 1
    xSum:7 + y:2 = 9
    ySum:1 + y:2 = 3
    xSum:9 + y:3 = 12
    ySum:3 + y:3 = 6
    ySum:12 + y:4 > 6 break yLoop
    xSum:12 + y:1 = 13
    ySum:0 + y:1 = 1
    xSum:13 + y:2 = 15
    ySum:1 + y:2 = 3
    xSum:15 + y:3 = 18
    ySum:3 + y:3 = 6
    ySum:18 + y:4 > 6 break yLoop
    xSum:18 + y:1 = 19
    ySum:0 + y:1 = 1
    xSum:19 + y:2 > 20 break xLoop
    

    注意标记:xLoop,yLoop

    相关文章

      网友评论

        本文标题:Swift4 基础部分:Control Flow

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