Swift control transfer statement

Source: Internet
Author: User

Tag: swift IOS objective-C

Control Transfer statements)

Control the transfer statement to change the execution sequence of your code. You can use it to redirect your code. Swift has four transfer control 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 immediately stop this iteration and start the next iteration. It is like saying "I have finished this loop iteration", but it does not leave the whole loop body.

 

Note:

 

In a for-condition-increment loop, after the continue statement is called, the iteration increment is still evaluated. The loop body continues to work as usual, but the Execution Code in the loop body will be skipped.

In the following example, the vowel and space characters in a lower-case string are removed, and a fuzzy short sentence is generated:

 

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, if a vowel or space character is matched, The continue statement is called to end the iteration and start the next iteration. This action does not process the switch when matching the vowel and space characters, rather than making every matched character printed.

 

 

Break

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

 

 

Break in loop statements

 

When break is used in a loop body, the execution of the loop body is immediately interrupted, and the first line of code after braces (}) indicating the end of the loop body is jumped. There will be no more code executed for this loop iteration, or the next loop iteration will be generated.

 

 

Break in the switch statement

 

When break is used in a switch code block, the execution of the switch code block is immediately interrupted, and the first line of code after braces (}) indicating the end of the switch code block is redirected.

 

This feature can be used to match or ignore one or more branches. Because swift switches need to contain all branches and do not allow empty branches, sometimes you need to specifically match or ignore a branch to make your intention more obvious. When you want to ignore a branch, you can write the break statement in the branch. When the branch is matched, the break statement in the branch immediately ends the switch code block.

 

Note:

 

When a switch Branch only contains comments, a compilation error is reported. Note is not a code statement and cannot make the switch branch neglected. You can always use break to ignore a branch.

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

 

Let numbersymbol: character = "3" // number 3var possibleintegervalue: int in simplified Chinese? Switch numbersymbol {Case "1 ","? "," 1 ","? ": Possibleintegervalue = 1 case" 2 ","? "," 2 ","? ": Possibleintegervalue = 2 case" 3 ","? "," 3 ","? ": Possibleintegervalue = 3 case" 4 ","? "," 4 ","? ": Possibleintegervalue = 4 default: break} If let integervalue = possibleintegervalue {println (" the integer value of \ (numbersymbol) is \ (integervalue ). ")} else {println (" an integer value cocould not be found for \ (numbersymbol ). ")} // output" The integervalue of three is 3."


In this example, check whether numbersymbol is one of the numbers 1 to 4 in Latin, Arabic, Chinese, or Thai. If it is matched, the switch branch statement is given to int? The Type Variable possibleintegervalue sets an integer.

 

After the switch code block is executed, the following code uses the optional binding to determine whether the possibleintegervalue has been set. Because of the optional type, possibleintegervalue has an implicit Initial Value nil. Therefore, when possibleintegervalue was set to one of the first four branches of the switch code block, the binding is successful.

 

In the above example, it is unrealistic to enumerate all the possibilities of character. Therefore, the default branch is used to include all the situations where no matching characters are found above. Because this default branch does not need to execute any action, it only writes one break statement. Once it falls into the default branch, the break statement completes all the code operations of the branch. The Code continues to run the if let statement.

 

 

Penetration (fallthrough)

Switch in swift does not fall into the next case branch from the previous case Branch. On the contrary, as long as the first matched case Branch completes the statements it needs to execute, the entire switch code block completes its execution. In contrast, the C language requires that you insert the break statement to the end of each switch branch to prevent automatically falling into the next case Branch. This feature of swift to avoid falling into the next branch by default means that its switch function is clearer and more predictable than that of C language, it can avoid errors caused by the unintentional execution of multiple case branches.

 

If you really need the fallthrough feature of the C style, you can use the fallthrough keyword in each case branch that requires this feature. The following example uses fallthrough to create a Numerical Description statement.

 

Let integertodescribe = 5var description = "The number \ (integertodescribe) is" Switch integertodescribe {Case 2, 3, 5, 7, 11, 13, 17, 19: description + = "a prime number, and also" fallthroughdefault: Description + = "an integer. "} println (description) // output" The number 5is a prime number, and also an integer."


This example defines a description variable of the string type and sets an initial value for it. The function uses the switch logic to determine the value of the integertodescribe variable. When the value of integertodescribe belongs to the moment of prime number in the list, this function adds a text in description to indicate that the number is a prime number. Then it uses the fallthrough keyword to "run" to the default branch. The default branch adds an additional piece of text at the end of the description. Now the switch code block has been executed.

 

If the value of integertodescribe does not belong to any prime number in the list, it does not match the first switch branch. There are no other special branches, so integertodescribe matches all the default branches.

 

After the switch code block is executed, use the println function to print the description of the number. In this example, number 5 is accurately recognized as a prime number.

 

Note:

 

The fallthrough keyword does not check whether it will fall into the matching condition in the executed case. Fallthrough simply connects code execution to the Execution Code in the next case, which is the same as the switch statement in the C language standard.

 

Labeled statements)

In swift, You can nest the loop body and switch code block in the loop body and switch code block to create a complex control flow structure. However, both the loop body and the switch code block can use the break statement to end the entire method body in advance. Therefore, it is useful to explicitly specify the loop body or switch code block to be terminated by the break statement. Similarly, if you have many nested loop bodies, it is very useful to indicate which loop bodies the continue statement wants to affect.

 

To achieve this, you can use tags to mark a loop body or switch code block. When break or continue is used, this tag can be used to control the interruption or execution of objects.

 

A tag-containing statement is generated by placing a tag in front of the same row of the statement's keywords, and a colon is required after the tag. The following is a while loop body syntax. The same rules apply to all loop bodies and switch code blocks.

 

`label name`: while `condition` {   `statements`}


The following example calls the break and continue statements in a label while loop body, which is an adapted version of the snake and ladder in the previous section. This time, the game added an additional rule:

 

To win the game, you must place it in 25th blocks.

If you move more than 25th blocks by throwing a dice, you must roll the dice again until the number of dice you throw is exactly enough to make you fall into 25th blocks.

 

The game board is the same as before:

 

 

 

The finalsquare, board, square, and diceroll values are initialized as before:

 

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


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

 

The while loop body's condition judgment statement is while square! = Finalsquare, which indicates that you must be in the 25 square.

 

Gameloop: While square! = Finalsquare {If ++ diceroll = 7 {diceroll = 1} switch square + diceroll {Case finalsquare: // get to the last square, when the game ends, break gameloop case Let newsquare where newsquare> finalsquare: // go beyond the last square and throw the dice again. Continue gameloop default: // valid square + = diceroll square + = Board [square]} println ("game over! ")


Roll the dice at the beginning of each loop iteration. Different from moving a player immediately after throwing a dice, a switch is used here to consider the possible results of each move, so as to determine whether the player can move this time.

 

If the number of dice moves players to the final square, the game will end. The break gameloop statement jump control is used to execute the first line of code after the while loop body, and the game ends.

If the number of dice will make the Player move beyond the last square, this movement is illegal and the player needs to roll the dice again. The continue gameloop statement ends the while loop iteration and starts the next loop iteration.

In all the remaining cases, the number of dice is legal. The player moves the dice several squares forward, and the game logic then processes whether the player is currently at the bottom of the Snake Head or ladder. At the end of this loop iteration, control the condition judgment statement that jumps to the while loop body and decide whether to continue executing the next loop iteration.

Note:

 

If the preceding break statement does not use the gameloop tag, it will interrupt the switch block instead of the while loop body. The gameloop label clearly shows the code block that break wants to interrupt. Note that when you call continue gameloop to jump to the next loop iteration, using the gameloop tag is not strictly required. In this game, there is only one loop body, so the continue statement will affect which loop body is unambiguous. However, the use of gameloop labels in the continue statement is harmless. In this way, the use of tags is followed, and the break gameloop next to it makes the game logic clearer and easier to understand.

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.