8.Swift Tutorial Translation Series-Conditions of control flow

Source: Internet
Author: User

3. Conditional statements

It is often necessary to run different code based on different situations.

You may want to run an extra piece of code when the error occurs, or output it when a value becomes too high or too low. To implement these requirements, you can use conditional branching.

Swift provides two ways to implement conditional branching. This is the IF statement and the switch statement.

In general, if used in simple conditions that are less likely to be used, it would be better to use switch when encountering complex conditions with very many possibilities. Or, switch is useful when you want to infer what code to run based on pattern matching.

If statement

The simplest form of if only has a single if condition. The code in the if curly brace is only run when the condition is true:

var Temperatureinfahrenheit = 30if Temperatureinfahrenheit <= {<span style= "White-space:pre" ></span> println ("It ' s very cold. Consider wearing a scarf. ")} Prints "It ' s very cold. Consider wearing a scarf. "
The above example checks whether the temperature is less than or equal to 32 degrees (water icing problem, not Celsius bar). The assumption is that the output statement will run, assuming that it does not run, and then run the statement after the if brace.

The IF statement can also provide an alternative block of statements. is the Else branch, and the else code is run when the IF condition evaluates to False. The following is the code that includes else:

Temperatureinfahrenheit = 40if Temperatureinfahrenheit <= {<span style= "White-space:pre" ></span> println ("It ' s very cold. Consider wearing a scarf. ")} else {<span style= "White-space:pre" ></span>println ("It's not so cold. Wear a T-shirt. ")} Prints "It ' s not so cold. Wear a T-shirt. "

There will always be one of two branches running. Because the temperature has risen to 40 degrees. It's already higher than 32 degrees. So the Else branch is running.

You can also link multiple if, using a number of other branches:

Temperatureinfahrenheit = 90if Temperatureinfahrenheit <= {<span style= "White-space:pre" ></span> println ("It ' s very cold. Consider wearing a scarf. ")} else if Temperatureinfahrenheit >= <span style= "White-space:pre" ></span>println ("It ' s really warm. Don ' t forget to wear sunscreen. ")} else {<span style= "White-space:pre" ></span>println ("It's not so cold. Wear a T-shirt. ")} Prints "It ' s really warm. Don ' t forget to wear sunscreen. "
An If statement is added here to respond to particularly hot temperatures. The last else is still there. Used as a response to a temperature that is neither too hot nor too cold.

Just the last else is optional, assuming that the various situations do not have to be handled by all:

Temperatureinfahrenheit = 72if Temperatureinfahrenheit <= {<span style= "White-space:pre" ></span> println ("It ' s very cold. Consider wearing a scarf. ")} else if Temperatureinfahrenheit >= <span style= "White-space:pre" ></span>println ("It ' s really warm. Don ' t forget to wear sunscreen. ")}
In this example, the temperature is not too cold to run if. It's not too hot to run else if. So there's nothing out there.

Switch statement

The switch statement matches a value to a number of possible scenarios.

Then run the first match on the corresponding code on the case.

The switch statement provides an alternative to the IF statement for a variety of possible scenarios.

The simplest form of a switch is that the value of a simple type is equal to several values of the same type:

Switch some value to consider {<span style= "White-space:pre" ></span>case value 1: <span style= " White-space:pre "></span>respond to Value 1<span style=" White-space:pre "></span>case value 2, Value 3: <span style= "White-space:pre" ></span>respond to value 2 or 3<span style= "White-space:pre" > </span>default:<span style= "White-space:pre" ></span>otherwise, do something else}
A switch statement consists of several case that may match.

In addition to the more special values. Swift also provides several ways to specify a more complex matching pattern for each case. These are described later in this chapter.

Each case of switch is a separate running branch, and the switch statement determines which branch is to be run.

The switch statement must be intact, meaning that all considerations must match a case.

It is best to provide a case for every possible situation, and you can define a default condition, assuming that the default branch is run with no previous match, the default branch uses Defaultkeyword and must come out after all the cases.

The following example uses the switch statement to check for a separate lowercase letter somecharacter:

Let Somecharacter:character = "E" switch somecharacter {<span style= "White-space:pre" ></span>case "a", "E", "I", "O", "U": <span style= "White-space:pre" ></span>println ("\ (somecharacter) is a vowel") <span style= "  White-space:pre "></span>case" B "," C "," D "," F "," G "," H "," J "," K "," L "," M "," N "," P "," Q "," R "," s "," T "," V ", "W", "X", "Y", "Z": <span style= "White-space:pre" ></span>println ("\ (somecharacter) is a consonant") < Span style= "White-space:pre" ></span>default:<span style= "White-space:pre" ></span>println ("\ (Somecharacter) is not a vowel or a consonant ")}//prints" E is a vowel "
The first case of switch above matches the arbitrary vowel letter. The second case matches the arbitrary consonant letter. It is not possible to write all the other letters, so the default is used to match random characters except vowels and consonants. Plus this default guarantees the completeness of the switch statement.

No implicit sequential runs

In contrast to the switch in C or OC, the SWIFT switch statement does not go back to the case after the matching case, and when the program matches to a case, the code block that runs the case, switch ends. You do not need to use the break statement at the end of a code block.

This makes the switch statement more secure and simpler than C, avoiding the fact that the program runs several case because of forgetting to write a break.

NOTE that if you think there is no break to look at awkward, you can also add.

Each case must include at least one statement. The following is wrong because the first case is empty:

Let Anothercharacter:character = "a" switch anothercharacter {<span style= "White-space:pre" ></span>case "a ": <span style=" White-space:pre "></span>case" A ": <span style=" White-space:pre "></span> println ("The Letter A") <span style= "White-space:pre" ></span>default:<span style= "White-space:pre" ></span>println ("Not the letter A")}//this would report a compile-time error
This may not be the same as the C language, the switch statement will not match "a" and "a" at the same time, but to case "a": the compilation Error "does not contain any executeable statements (excluding any statement that can be run)". This avoids accidentally running from one case to another. Make the code safe and intent clear.

If you want a case to match multiple cases, use commas to separate them. And very long to be able to branch write:

Switch some value to consider {<span style= "White-space:pre" ></span>case value 1, <span style= " White-space:pre "></span>   value 2: <span style=" White-space:pre "></span>statements}
NOTE that you can use Fallthroughkeyword if you want the matching hit to run in the following case sequence. The following will also be introduced specifically.

Range Matching

The case-matching value of switch can also be used in the range.

The following example uses a numeric range to display the natural language form of a number

Let count = 3_000_000_000_000let countedthings = ' stars in the Milky ' "Var naturalcount:stringswitch count {case 0:
   
    naturalcount = "No" case 1...3:    naturalcount = ' A few ' case 4...9:    naturalcount = ' Several ' case 10...99:    Naturalcount = "Tens of" case 100...999:    naturalcount = "Hundreds of" case 1000...999_999:    naturalcount = " Thousands of "default:    Naturalcount =" millions and millions of "}println (" there is \ (Naturalcount) \ (countedthings) .") Prints "There is millions and millions of stars in the Milky."
   
Meta-group

You can use tuples in a switch statement to infer multiple values. Elements in a tuple can each be compared by a single value or a range. Or you can use underscores to make him match random values.

The following example uses a tuple (int, int) of type (x, y) to represent a point and then classifies the points:

Let Somepoint = (1, 1) switch somepoint {case (0, 0):    println ("(0, 0) was at the origin") case (_, 0):    println ("(\ (so mepoint.0), 0) case (0, _):    println ("(0, \ (somepoint.1)) was on the y-axis") case ( -2...2, -2...2): 
   println ("(\ (somepoint.0), \ (Somepoint.1)) is inside the box") Default:    println ("(\ (somepoint.0), \ (Somepoint.1) ) is outside of the box ")}//prints" (1, 1) is inside the box "

The switch statement infers whether the point is at the origin (0,0). Or on the red X-axis, or on the Orange y-axis, or in the blue area, or outside the blue area.

Unlike C, Swift can use repeated values in multiple case, in fact (0,0) is able to match the above four case.

But even if more than one case can match, the first match will be run.

So the point (0,0) matches the first (0,0) situation, and the others are ignored.

Value binding

The case can bind the value of his match to a temporary constant or variable, and then use it in the code block of the case.

This is the value binding, because the value is only bound to a temporary constant or variable in the case code block.

The following examples are almost identical to the above

Let Anotherpoint = (2, 0) switch Anotherpoint {case (Let x, 0):    println ("On the x-axis with a X value of \ (x)") Case (0 , let y):    println ("on the y-axis with a Y value of \ (y)") (x, y):    println ("somewhere else at (\ (x), \ (y)") )}//prints "on the x-axis with an X value of 2"

The switch statement infers whether the point is on the x-axis, or on the y-axis, or somewhere else.

Three case life the constants x and Y are used to temporarily get the values of x or Y or x and y from the tuple anotherpoint. The first Case,caes (let x,0) matches no matter what the y-coordinate is 0 points. and assign this point to the x-coordinate to the temporary constant x, the second case, the case (0, let y) to match all the x-coordinate points of 0, and then assign this point y-coordinate to the temporary constant Y.

Only if the temporary constant is life. That constant can be used in the code block of this case.

For this example, they are used to output the values of coordinates.

Note that this switch has no default, because the last case let (x, y) uses two placeholders, then he will match all the points. So there is no need to add the default, this switch is very complete.

In the example above. X and y are defined as constants, because we don't have to change the value of coordinates in the case. Suppose you want to declare a variable and use Varkeyword, assuming it is, the temporary variable should have been created and initialized with the appropriate value.

Any change to the variable is only valid in this case.

where

Case can also use the WHERE statement to add many other conditional inferences

The following examples classify the points:

Let Yetanotherpoint = (1,-1) switch Yetanotherpoint {case let (x, y) where x = = y:    println ("(\ (x), \ (y)) are on the Lin E x = = y ") case let (x, y) where x = = y:    println (" (\ (x), \ (y)) is on the line x = y ") case let (x, y):    println (" ( \ (x), \ (y)) is just some arbitrary point ")}//prints" (1,-1) are on the line x = = y "

Switch infers whether the point is on a Green Line (x=y), or on a Purple Line (x = y). or anywhere else.

Each of the three case declarations constants x and Y, temporarily storing a point coordinate value.

These constants are also used as part of the where statement in the case. To create a dynamic filter. This case is only matched if the current matching point satisfies where the expression evaluates to True.

As in the previous example, the last case matches all the remaining points, so the switch does not add the default.


4. Control transfer Statements

Control transfer statements can change the order in which code is run by transferring control from one piece of code to another. Swift has four types of control transfer statements

Continue

Break

Fallthrough

Return

The first three types are described below. The last return will be described in the chapter of the function.

Continue

The continue statement tells the Loop to stop the current loop and then start the next loop.

In other words, "This cycle has run out" and does not jump out of the loop altogether.

NOTE in the cycle of the for-condition-increment type. Assuming that the continue statement is used, the increment statement will still be run. The order of the loops itself is normal, just the loop body being skipped.

The following example strips out the vowels and spaces in a lowercase string, resulting in a phrase that has no meaning at all.

Let Puzzleinput = "great minds think alike" var puzzleoutput = "" for character in Puzzleinput {    switch character {    Case "A", "E", "I", "O", "U", "":        continue    Default:        puzzleoutput + = character    }}println (puzzleoutput)/ /Prints "Grtmndsthnklk"
The above code uses continue only if it encounters a vowel or a space. The current loop is terminated and the next cycle is started.

This allows the switch to only match and ignore vowels and spaces, rather than requiring the code block to match all the characters that need to be output.

Break

The break statement terminates the current entire control flow. Break can be used to switch or loop in order to exit the entire switch or loop in advance.

Break in the Loop

Assuming that a break is used in a looping statement, the entire loop is immediately terminated and the code behind the curly brace that runs the loop is transferred.

The current loop will not be run, and the next and future loops will not be run.

Break in Switch

Assume that you use break in switch. The switch is immediately terminated and the switch code is started. can use break to match and ignore one or more cases. Because Swift's switch is complete and does not agree with the empty branch. Sometimes the intent is more pronounced in order to be useful and to ignore certain situations. Then break is the only code in the case code block that you want to ignore. When that case is matched, the entire switch statement is immediately terminated.

NOTE that the case has only a gaze. The compiler will report a compilation error.

Gaze is not a statement. It is not a case to be ignored. Let's say break if you want the case to be ignored.

The following example uses switch to infer whether a character represents one of the following four languages.

For brevity, this side matches multiple values in a case:

Let Numbersymbol:character = "three"  //Simplified Chinese for the number 3var Possibleintegervalue:int?

Switch Numbersymbol {case "1", "?", "One", "?": Possibleintegervalue = 1case "2", "?", "Two", "?": Possibleintegervalu E = 2case "3", "?", "Three", "?": Possibleintegervalue = 3case "4", "?", "Four", "?": Possibleintegervalue = 4default: break}if Let IntegerValue = possibleintegervalue { println ("the integer value of \ (Numbersymbol) is \ (IntegerValue) .")} else { println ("An integer value could not being found for \ (Numbersymbol).")} Prints "The integer value of three is 3."

The example above examines numbersymbol to determine whether it is Latin, Arabic numerals. 1,2,3,4 in Chinese or Thai. If a match is found, the case assigns a value to the optional variable possibleintegervalue.

When switch runs out, use an optional value binding to infer whether the Possibleintegervalue has a value. Since this optional variable is implicitly initialized with nil. So suppose that only if a case assigns a value to him, the following if will pass.

It is not practical to list all possible characters in the above example, so a deault is used to match all the remaining characters. This branch does not need to be done in any operation. So just write a break statement. Only the last default is matched, and the entire switch is terminated by a break. Start running the following if.

Fallthrough

The SWIFT switch statement assumes that a case is no longer running down, and that the code that runs the case is finished with the entire switch. In C, however, it is required to add a break at the end of the case to have this effect. Avoiding default hanging runs means that Swift's switch statement is more concise and predictable than c, and avoids having to run other case as a result of forgetting to write a break.

Let's say you do need a feature that runs through like C. You can satisfy by using Fallthroughkeyword. The following self-care uses Fallthrough to create a textual descriptive narrative of the numbers:

Let Integertodescribe = 5var Description = "the number \ (integertodescribe) are" switch Integertodescribe {case 2, 3, 5, 7, One, all,    +: Description + = "A prime number, and also"    Fallthroughdefault:    description + = "an Integer."} println (description)//Prints "The number 5 is a prime number, and also an integer."
The example declares a string variable description and assigns it an initial value.

Then use switch to test the value of the Integertodescribe. The assumption is a prime number in the first case. Just behind the description, add a text that shows that this number is prime. Then use Fallthroughkeyword to allow the program to proceed directly to the next case Default,default the description added other descriptive narrative information, and then the entire switch ended.

Suppose Integertodescribe is not in the first case. The first case will not be matched. There are no other special branches, so they are matched by default.

When the switch statement is finished running, the descriptive narrative of the number is used to output the println function.

In this example, the number 5 is correctly recognized as prime.

NOTE Fallthrough does not check the conditions of the next branch that will be matched, he simply lets the program go directly to the next branch, just like the C standard switch statement.
Label statement

You can implement complex control flow structures by nesting other switch or loops within a switch or loop.

Both switch and loop can use the break statement to end the program prematurely. But sometimes you need to specify which loop or switch you want to jump out of. Let's say you've nested several loops. It is very necessary to indicate which loop the break should jump out of.

To do this, you can set a label for the loop or switch, and then break or continue to add the tag. You can let break or continue affect the loop or switch.

The label statement is preceded by a label name plus a colon in front of the statement itself. The following is a sample that uses a label for a while statement. This rule is common for all loops and switch:

Label Name:while Condition {    statements}
The following example uses tagged break and continue statements to implement the game of Snakes and ladders written once again.

The rules of the game add one: when and only when you are in the 25th lattice of the time to calculate the clearance

Suppose that a dice is then jumped to 25, and then another dice. Until you stand on the 25 grid. The game board is the same as the previous one:

Finalsquare,borad,square and Diceroll are initialized in the same way 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 time using a while loop and a switch to implement the game logic. The while Loop has a label gameloop, which indicates that this is the main loop of the game.

The loop condition of the while loop is while square! = Finalsquare. That means you have to be on the 25th grid to pass:

Gameloop:while Square! = finalsquare {    if ++diceroll = = 7 {diceroll = 1}    switch Square + diceroll {case    fi  Nalsquare:        //Diceroll would move us to the final square, so the game was over break Gameloop case let    newsquare where Newsquare > Finalsquare:        //Diceroll would move us beyond the final square, so roll again continue Gamelo        OP    Default:        //This was a valid move, so find out its effect        square + diceroll        square + + board[square]
   }}println ("Game over!")
Each cycle is preceded by a dice. But this is not the basis of the dice to move directly. Instead, a switch is used to infer whether or not to agree to move based on the result of the move:

Assuming that the dice can move you to the last lattice, the game is over, and the break Gameloop statement shifts the program to the while loop, and the game ends.

Assuming that this boson moves you out of the chessboard, the movement is illegal, and you want to roll the dice again. The Continue Gameloop statement ends the loop that is currently in progress and starts the next loop.
Other circumstances. Moving is legal and will not allow you to cross the border.

You move in accordance with the number of dice, and then check that the current position is not a snake head or ladder can move.

Then the current loop ends and returns to the while conditional statement to infer whether the next loop is required.

NOTE that the break statement above does not work with the gameloop tag. That break simply jumps out of the switch without terminating the entire while loop. Using the Gameloop tag clearly indicates which statement needs to end.

Also note that when you want to use continue for the next cycle in the Gameloop loop, you do not have to gameloop the tag. Since there is only one loop in the game, it is not necessary to indicate who continue is working for.


But it doesn't hurt you to use it.

This makes the program logic clear and easy to understand.

8.Swift Tutorial Translation Series-Conditions of control flow

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.