Swift programming language Learning 4.3--control statements

Source: Internet
Author: User



Control pass-through statements (controlled Transfer statements)



The control transfer statement changes the order in which you run the code, through which you can implement the code jump. Swift has four kinds of control transfer statements.






Continue



Break



Fallthrough



Return



We will discuss the continue, break, and Fallthrough statements below. The return statement will be discussed in the function section.









Continue



The continue statement tells a loop body to stop the iteration of the loop immediately, and again to start the next iteration of the loop. It's like saying, "I've run out of this loop iteration," but I'm not going to leave the whole loop body.






Attention:






In a for-conditional increment (for-condition-increment) loop body, the iteration increment is still evaluated after the continue statement is called. The loop body continues to work as usual, except that the running code in the loop body is skipped.



The following example removes the vowel and space characters from a lowercase string, creating a vague phrase:



Let puzzleInput = "great minds thinkalike"
Var puzzleOutput = ""
For character in puzzleInput {
    Switch character {
    Case "a", "e", "i", "o", "u", " ":
        Continue
    Default:
        puzzleOutput += character
     }
}
Println(puzzleOutput)
    // output "grtmndsthnklk"


In the above code, just to match the vowel letter or the space character, call the continue statement, so that the loop iteration ends, the next loop iteration from the beginning. This behavior causes switch to match the vowel and space characters without processing, rather than having each matched character printed.









Break



The break statement immediately ends the operation of the entire control flow. You can use the break statement when you want to end a switch block of code or a loop body earlier.









Break in a looping statement






When a break is used in a loop body, the run of the loop body is immediately interrupted and then jumps to the first line of code after the curly brace (}) that represents the end of the loop body. No more code for this loop iteration will be run, and there will be no next iteration of the loop.









Break in a Switch statement






When a break is used in a switch block, the switch code block runs immediately, and jumps to the first line of code after the curly brace (}) that represents the end of the switch code block.






Such a feature can be used to match or omit one or more branches. Because Swift's switch needs to include all branches and does not agree with an empty branch, sometimes it is necessary to deliberately match or omit a branch in order to make your intentions more apparent. Then when you want to ignore a branch, you can write a break statement within that branch. When that branch is matched, the break statement within the branch ends the switch code block immediately.






Attention:






When a switch branch includes only the gaze, it is reported as a compile-time error. Gazing is not a code statement and does not allow the switch branch to achieve the ignored effect. You can always use break to ignore a branch.



The following example uses switch to infer whether a character value represents one of the following four languages. For brevity, multiple values are included in the same branch case.


Let numberSymbol: Character = "three" // the number in Chinese Simplified 3
Var possibleIntegerValue: Int?
Switch numberSymbol {
Case "1", "?", "one", "?":
    possibleIntegerValue = 1
Case "2", "?", "two", "?":
    possibleIntegerValue = 2
Case "3", "?", "three", "?":
    possibleIntegerValue = 3
Case "4", "?", "four", "?":
    possibleIntegerValue = 4
Default:
    Break
}
If let integerValue = possibleIntegerValue{
    Println("The integer value of \(numberSymbol) is\(integerValue).")
} else {
    Println("An integer value could not be found for\(numberSymbol).")
}
// output "The integervalue of three is 3."


This sample examines whether Numbersymbol is one of 1 to 4 in Latin, Arabic, Chinese, or Thai. Assuming that the switch branch statement is matched to an int? type variable possibleintegervalue, set an integer value.






When the switch code block finishes running, the next code infers whether the Possibleintegervalue was previously set by using an optional binding. Because of the optional type, the Possibleintegervalue has an implicit initial value of nil, so the optional binding will be judged successful only if Possibleintegervalue has been given a value in one of the first four branches of the switch code block.






In the example above, it is unrealistic to enumerate all of the possibilities of character, so use the default branch to include all cases where there are no matches to characters. Because the default branch does not need to run any action, it simply writes a break statement. Once it falls into the default branch, the break statement completes all code operations on that branch, and the code continues down to start running the IF let statement.









Through (Fallthrough)



The switch in Swift does not fall from the previous case branch into the next case branch. Instead, just the first match to the case branch completes the statement it needs to run, and the entire switch block completes its run. In contrast, the C language requires that you display the Insert break statement to the end of each switch branch to prevent you from actively falling into the next case branch. The nature of Swift's avoidance of default falling into the next branch means that its switch function is clearer and more predictable than the C language, and avoids the errors caused by the unconscious running of multiple case branches.






Suppose you do need a C-style through (Fallthrough) feature, and you can use Fallthroughkeyword in every case branch that requires that feature. The following example uses Fallthrough to create a descriptive statement of a number.



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."
}
Println(description)
// output "The number 5is a prime number, and also an integer." 


This example defines a variable of type string description and sets an initial value for it. The function uses the switch logic to infer the value of the Integertodescribe variable. When the value of Integertodescribe belongs to one of the prime numbers in the list, the function adds a paragraph of text after description to indicate that the number is a prime. It then uses Fallthroughkeyword to "run through" into the default branch. The default branch joins an extra piece of text at the end of the description, and the switch code block runs out.






Assuming that the value of Integertodescribe is not part of the list, no matter what prime number, it does not match to the first switch branch. There are no other special branching cases, so integertodescribe matches to include all of the default branches.






When the switch code block finishes running, use the PRINTLN function to print a descriptive narrative of the number. In this example, the number 5 is accurately identified for a prime.






Attention:






Fallthroughkeyword does not check its next match condition that will fall into the running case. Fallthrough simply keeps the code running to connect to the running code in the next case, which is the same as the switch statement attribute in the C language standard.






Tagged statement (labeled statements)



In Swift, you can nest loops and switch blocks in the loop body and switch code blocks to create complex control flow structures. However, both the loop body and the switch code block can use the break statement to prematurely end the entire method body. Therefore, it is very useful to indicate which loop body or switch code block the break statement wants to terminate. Similarly, suppose you have a lot of nested loops, and it is useful to indicate which loop body the continue statement wants to affect.






To do this, you can use tags to tag a loop body or switch block of code, and when you use break or continue, you can control that tag to represent the object's interruption or operation.






A tagged statement is generated by placing a label in front of the same line in the keyword of the statement, with a colon followed by the label. The following is a while loop body syntax, the same rules apply to all the loop body and switch code block.



' Label name ': While ' condition ' {   ' statements '}


The following example calls the break and continue statements in a labeled while loop body, which is an adapted version number for snakes and ladders in the previous section. This time, the game adds an extra rule:






In order to win, you have to just fall into the 25th block.



Assuming that a roll of dice makes you move beyond the 25th block, you have to roll the dice again until the number of dice you throw is exactly where you can fall in the 25th block.






The game board is the same as before:












The initialization of values Finalsquare, board, Square, and Diceroll is also the same as before:


let finalSquare = 25
var board = Int[](count: finalSquare + 1,repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09]= +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22]= -02; board[24] = -08
var square = 0
var diceRoll = 0


This version of the game uses the while loop body and the switch method block to implement the game logic. The while loop body has a label name Gameloop to indicate that it is the main loop of the snake and the ladder.






The conditional inference statement for the while loop body is the while square!=finalsquare, which indicates that you must just fall in the square 25.


gameLoop: while square != finalSquare {
    If ++diceRoll == 7 { diceRoll = 1 }
    Switch square + diceRoll {
    Case finalSquare:
        // Go to the last square and the game is over
        Break gameLoop
    Case let newSquare where newSquare > finalSquare:
        // Go beyond the last square and throw a dice
        Continue gameLoop
    Default:
        // This move is valid
        Square += diceRoll
        Square += board[square]
     }
}
Println("Game over!")


Roll the dice at the beginning of each iteration of the loop. Unlike the previous player, which moves the dice immediately, the switch is used to consider the possible results of each move, which determines whether the player can move this time.






Assuming the dice number just moves the player to the last square, the game is over. Break Gameloop statement Jump controls the first line of code after running the while loop body, the game ends.



Assuming that the number of dice will make the player move beyond the last square, then this move is not legal, the player needs to roll the dice again. The Continue Gameloop statement ends the iteration of this while loop and starts the next iteration of the loop.



In all remaining cases, the number of dice produced is the legal movement. The player moves the dice several squares forward, then the game logic handles whether the player is currently at the bottom of the snake head or ladder. At the end of this loop iteration, the control jumps to the conditional inference statement of the while loop body, and then decides whether the next iteration of the loop can continue to run.



Attention:






Assuming that the break statement above does not use the gameloop tag, it interrupts the switch code block rather than the while loop body. Using the Gameloop tag is a clear indication of which block of code the break is trying to interrupt. At the same time, note that it is not strictly necessary to use the Gameloop tag when calling continue Gameloop to jump to the next iteration of the loop. Because in this game, there is only one loop body, so the continue statement will affect which loop body is not ambiguous. However, it is not harmful to use Gameloop tags with continue statements. This is done in accordance with the rules of the tag, and at the same time the break Gameloop next to it can make the game logic clearer and easier to understand.



Swift programming language Learning 4.3--control statements


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.