3. conditional statements
It is often necessary to execute different codes according to different situations. You may want to execute an extra code when an error occurs, or output it to a value that is too high or too low. To meet these requirements, you can use conditional branches.
Swift provides two methods to implement conditional branches, that is, if statements and switch statements. Generally, if is used in simple conditions with few possible conditions. It is better to use switch when there are many possibilities for complex conditions, or it is also useful to switch the code to be executed based on the pattern matching.
If statement
The simplest form of IF is only a separate if condition. The code in the if braces is executed only when the condition is true:
var temperatureInFahrenheit = 30if temperatureInFahrenheit <= 32 {<span style="white-space:pre"></span>println("It's very cold. Consider wearing a scarf.")}// prints "It's very cold. Consider wearing a scarf."In the above example, check whether the temperature is less than or equal to 32 degrees (the water is frozen, not degrees Celsius ). If yes, the output statement is executed. If not, the statement is not executed. Then, the statement following the if braces is executed.
The IF statement can also provide another optional statement block, that is, the else branch. When the if condition is calculated as false, else code is executed. The following code contains else:
temperatureInFahrenheit = 40if temperatureInFahrenheit <= 32 {<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 that cold. Wear a t-shirt.")}// prints "It's not that cold. Wear a t-shirt."
One of the two branches is always executed. Because the temperature has increased to 40 degrees, it is higher than 32 degrees, so the else branch is executed.
You can also link Multiple if strings to use more branches:
temperatureInFahrenheit = 90if temperatureInFahrenheit <= 32 {<span style="white-space:pre"></span>println("It's very cold. Consider wearing a scarf.")} else if temperatureInFahrenheit >= 86 {<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 that cold. Wear a t-shirt.")}// prints "It's really warm. Don't forget to wear sunscreen."Here, an if statement is added to respond to particularly hot temperatures. The last else is still used as a response to a temperature that is neither too hot nor too cold.
However, the last else is optional. If you do not need to handle all the problems:
temperatureInFahrenheit = 72if temperatureInFahrenheit <= 32 {<span style="white-space:pre"></span>println("It's very cold. Consider wearing a scarf.")} else if temperatureInFahrenheit >= 86 {<span style="white-space:pre"></span>println("It's really warm. Don't forget to wear sunscreen.")}In this example, the temperature is neither too cold to execute if, nor too hot to execute else if, so nothing is output.
Switch statement
A switch statement matches a value with several possible conditions. Then execute the code corresponding to the first matching case. The switch statement provides another option for if statements in multiple possible cases.
The simplest form of a switch is to compare the values of a simple type with several values of the same type to see if they are equal:
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 multiple possible matching cases. In addition to special values, swift also provides several methods to specify more complex matching modes for each case. These contents will be introduced later in this chapter.
Each case of a switch is an independent Execution Branch. The switch statement determines which branch is executed. The switch statement must be complete, that is to say, all situations to be considered must match a case. It is best to provide a case for every possible situation. You can also define a default case. If none of the above conditions match, the default branch will be executed, the default branch uses the default keyword and must come out after all cases.
The following example uses the switch statement to check 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 the switch matches any vowel and the second case matches any consonants. It is not possible to write all other letters, so the default character is used to match any character except the vowel and the consonants. The addition of this default ensures the completeness of the switch statement.
No execution in implicit Sequence
Compared with the switch in C or oC, the switch statement of Swift does not match the case after the matched case one by default. When the program matches a case, the code block of the case is executed, the switch ends, and the break statement is not required at the end of the code block. This makes the switch statement safer and simpler than C, and avoids the execution of several cases due to forgetting to Write Break.
Note: If you don't think break is awkward, you can add it.
Each case must contain at least one statement. The following is an error 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 will report a compile-time errorThis is different from the C language. The switch statement does not match "A" and "A" at the same time, but gives case "": the compilation error "does not contain any executeable statements (excluding any executable statements)" is reported )". This avoids the accidental execution from one case to another, so that the code is safe and the intent is clear.
To match multiple cases in one case, use commas (,) to separate them, and a long case can be written in a branch:
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: If you want to perform the case sequence after matching hits, you can use the fallthrough keyword, which will be introduced later.
Range matching
The range of case matching values of the switch can also be used. The following example uses a number range to display the natural language of a number.
let count = 3_000_000_000_000let countedThings = "stars in the Milky Way"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 are \(naturalCount) \(countedThings).")// prints "There are millions and millions of stars in the Milky Way.”Tuples
You can use tuples in the switch statement to determine multiple values. Each element in the tuples can be compared by a single value or a certain range. Alternatively, you can use underscores to match any value.
The following example uses (INT, INT) type tuples (x, y) to represent a vertex, and then classifies the vertex:
let somePoint = (1, 1)switch somePoint {case (0, 0): println("(0, 0) is at the origin")case (_, 0): println("(\(somePoint.0), 0) is on the x-axis")case (0, _): println("(0, \(somePoint.1)) is 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 determines whether the vertex is in the origin (0, 0), red X axis, orange Y axis, or in the blue area, or outside the blue area.
Unlike C, Swift can use repeated values for multiple cases. In fact, () can match the above four cases. However, even if multiple cases can be matched, the first matched case will be executed. So the point (0, 0) will match the first (0, 0), and the other will be ignored.
Value binding
Case can bind the matched value to a temporary constant or variable, and then use it in the code block of case. This is the value binding, because the value is only bound to a temporary constant or variable in the case code block.
The example below is similar to the above
let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0): println("on the x-axis with an x value of \(x)")case (0, let y): println("on the y-axis with a y value of \(y)")case let (x, y): println("somewhere else at (\(x), \(y))")}// prints "on the x-axis with an x value of 2”
The switch statement determines whether the vertex is on the X axis, Y axis, or elsewhere.
The three cases contain constants X and Y, which are used to temporarily obtain values of X, Y, X, and Y from the tuples anotherpoint. The first case, caes (Let X, 0) matches any point whose y coordinate is 0, and assigns the X coordinate of this point to the temporary constant X, the second case, case (0, let y) matches all the points whose X coordinates are 0, and then assigns the Y coordinates of this point to the temporary constant y.
As long as a temporary constant is alive, this constant can be used in the code block of this case. In this example, they are used to output coordinate values.
Note that the switch does not have default, because the last case Let (X, Y) uses two placeholders, then it will match all vertices, so there is no need to add default, this switch is complete.
In the above example, X and Y are defined as constants because we do not need to modify the coordinates in case. If you want to declare a variable, use the VaR keyword. If so, the temporary variable should have been created and initialized with the appropriate value. Any modification to this variable is only valid in this case.
Where
You can also use the where statement to add more condition judgments in case.
The following example classifies vertices:
let yetAnotherPoint = (1, -1)switch yetAnotherPoint {case let (x, y) where x == y: println("(\(x), \(y)) is on the line 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) is on the line x == -y”
Switch determines whether the vertex is in a green line (x = Y), Purple Line (x =-y), or elsewhere.
The constants X and Y are declared in the three cases, and the coordinate values of points are temporarily stored. These constants are also used as part of the where statement in case to create a dynamic filter. This case will be matched only when the current matching vertex meets the where expression and the calculation result is true.
Like in the previous example, the last case matches all the remaining vertices, so the switch does not add default.
4. Transfer control statement
The control transfer statement can transfer the control from one piece of code to another to change the execution sequence of the Code. Swift has four transfer control statements
Continue
Break
Fallthrough
Return
The first three types are introduced below. The last return will be introduced in the function section.
Continue
The continue statement tells the loop to stop the current loop and then start the next loop. That is to say, "This cycle task has been completed", rather than jumping out of the loop completely.
Note in the for-condition-increment loop, if you use the continue statement, the incremental statement will still be executed. The order of the Loop itself is normal, but the loop body is skipped.
In the following example, the vowels and spaces in lowercase strings are removed, and a phrase with no meaning is generated.
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 whenever it encounters a vowel or space. The current loop is terminated and the next loop starts. In this way, the switch can only match and ignore the vowels and spaces, instead of requiring the code block to match all the characters to be output.
Break
The break statement terminates the entire control flow. Break can be used in a switch or loop to exit the entire switch or loop in advance.
Break in Loop
If break is used in a loop statement, the entire loop is immediately terminated, and the Code following the braces of the execution loop is transferred. The current cycle will not be executed, and the next and future cycles will not be executed.
Break in Switch
If break is used in a switch, the entire switch is terminated immediately and the code after the switch is executed. You can use break to match and ignore one or more cases. Because the swift switch is complete and does not allow empty branch, sometimes the intention is more obvious to deliberately match and ignore some situations. Then, break is the only code sentence of the case code block to be ignored. When the case is matched, the entire switch statement is immediately terminated.
Note if case only contains comments, the compiler reports a compilation error. Annotations are neither statements nor case ignored. Use break if you want to ignore the case.
The following example uses switch to determine whether a character represents one of the following four languages. To make it simple, match multiple values in a case:
Let numbersymbol: character = "3" // Simplified Chinese for the number 3var possibleintegervalue: Int? 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 ). ")} // prints" the integer value of three is 3."The above example checks numbersymbol to determine whether it is a Latin, Arabic number, Chinese or Thai 1, 2, 4. If a match is found, the case assigns a value to the optional variable possibleintegervalue.
When the switch is executed, use the optional value binding to determine whether the possibleintegervalue has a value, because this optional variable is implicitly initialized using nil, therefore, the following if statement is passed only when a case is assigned a value.
Listing all the possible characters in the above example is impractical, so a deault is used to match all the remaining characters. This branch does not need to perform any operations, so it only writes one break statement. As long as the last default is matched, the entire switch is terminated by break and the following if is executed.
Fallthrough
If the switch statement of swift matches a case, it will not continue to be executed. The entire switch after the code of this case is executed ends. However, adding a break at the end of case in C can achieve this effect. By default, the switch statement of SWIFT is more concise and predictable than that of C, and other cases are executed because of forgetting to Write Break.
If you really need a feature that runs like C, you can use the fallthrough keyword. The following uses fallthrough to create a text description of a number:
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)// prints "The number 5 is a prime number, and also an integer.”In this example, the description of a string variable is declared and the initial value is assigned to it. Then, use switch to test the value of integertodescribe. If it is a prime number in the first case, add a text after description to indicate that this number is a prime number. Then, the fallthrough keyword is used to allow the program to continue directly to the next case default. The default case adds other description information to the description, and the entire switch ends.
If integertodescribe is not in the first case, the first case will not be matched. There are no other special branches, so it is matched by default.
After the switch statement is executed, the description of the number is output using the println function. In this example, number 5 is correctly recognized as a prime number.
Note fallthrough does not check the condition of the next branch to be matched. It simply allows the program to directly enter the next branch, just like the c Standard switch statement.
Label statement
You can nest other switches or loops in a switch or loop to implement a complex control flow structure. Both the switch and loop can use the break statement to terminate the program in advance. However, you sometimes need to specify the loop or switch you want to jump out. For example, you nested several loops to specify which loop the break should jump out.
To achieve this goal, you can set a tag for the loop or switch, and then add the tag after the break or continue, so that the break or continue can affect the loop or switch.
The label statement adds a label name and a colon Before the statement itself. The following example shows how to use a label for a while statement. This rule is applicable to all loops and switches:
label name: while condition { statements}The following example uses the break and continue statements with tags to re-implement the game of snakes and ladders written above. Add one rule for this game: When and only when you are in the 25th frame
If you throw a shard and Jump beyond 25, you can throw it again until you are standing on the 25 th grid. The game board is the same as above:
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, a while loop and a switch are used to implement the game logic. The while loop has a label gameloop, indicating that this is the main loop of the game.
The loop condition of the while loop is while square! = Finalsquare, that is to say, you must stand on the 25th mark to pass:
gameLoop: while square != finalSquare { if ++diceRoll == 7 { diceRoll = 1 } switch square + diceRoll { case finalSquare: // diceRoll will move us to the final square, so the game is over break gameLoop case let newSquare where newSquare > finalSquare: // diceRoll will move us beyond the final square, so roll again continue gameLoop default: // this is a valid move, so find out its effect square += diceRoll square += board[square] }}println("Game over!")Throw the cursor in each loop. However, instead of moving directly based on the cursor, the switch is used to determine whether to allow moving Based on the moving result:
If this hacker can move you to the last cell, the game will be over. The break gameloop statement will move the program to the while loop, and then the game will be over.
If the hacker moves you out of the Board, it is illegal. You have to throw the hacker again. The continue gameloop statement ends the ongoing loop and starts the next loop.
In other cases, mobile is legal and won't let you pass. You can move it according to the number in the seek, and then check whether the current position can be moved by a snake or ladder. Then the current loop ends and the while Condition Statement is returned to determine whether the next loop is required.
Note: If the preceding break statement does not apply to the gameloop tag, the break only jumps out of the switch and does not terminate the entire while loop. Using the gameloop tag, you can clearly specify the statement to end.
Note that you do not need to use the gameloop tag when you use the continue in the gameloop loop for the next loop. Because there is only one loop in this game, it is not necessary to specify who the continue works.
But you can use it. This makes the program logic clear and easy to understand.