Tag: swift IOS objective-C
Condition Statement
It is usually very useful to execute specific code according to specific conditions. For example, when an error occurs, you may want to run additional code; or, when the input value is too large or too small, displays a message to the user. To implement these functions, you need to use conditional statements.
Swift provides two types of conditional statements: If statement and switch statement. Generally, if statements are used when the conditions are relatively simple and few conditions are possible. The switch statement is more suitable for situations where the conditions are complex, there may be many situations, and pattern-matching needs to be used.
If
The simplest form of an if statement is to contain only one condition. The code is executed only when the condition is true:
VaR temperatureinfahrenheit = 30if temperatureinfahrenheit <= 32 {println ("it's very cold. consider wearing a scscarf. ")} // output" It's verycold. consider wearing a scscarf."
The above example checks whether the temperature is less than or equal to 32 degrees Fahrenheit (the freezing point of water ). If yes, a message is printed; otherwise, the code after the if block is executed without printing any messages.
Of course, if statements allow either of them, that is, when the condition is false, execute the else statement:
Temperatureinfahrenheit = 40if temperatureinfahrenheit <= 32 {println ("it's very cold. consider wearing a scscarf. ")} else {println (" It's not that cold. wear a t-shirt. ")} // output" It's notthat cold. wear a t-shirt."
Obviously, one of the two branches will be executed. Since the temperature has risen to 40 degrees Fahrenheit, it is not too cold and there is no need to enclose the scarf-so the else branch is triggered.
You can link Multiple if statements together, as shown below:
Temperatureinfahrenheit = 90if temperatureinfahrenheit <= 32 {println ("it's very cold. consider wearing a scscarf. ")} else if temperatureinfahrenheit> = 86 {println (" it's really warm. don't forget to wear sunscreen. ")} else {println (" It's not that cold. wear a t-shirt. ")} // output" It's reallywarm. don't forget to wear sunscreen."
In the above example, the additional if statement is used to determine whether it is particularly popular. The last else statement is retained to print messages that are neither cold nor hot.
In fact, the final else statement is optional:
temperatureInFahrenheit = 72if temperatureInFahrenheit <= 32 { println("It's very cold. Consider wearing a scarf.")} else if temperatureInFahrenheit >= 86{ println("It's really warm. Don't forget to wear sunscreen.")}
In this example, because it is neither cold nor hot, if or else if branches are not triggered, and no messages are printed.
Switch
The switch statement tries to match a value with several pattern statements. The switch statement executes the corresponding code based on the first matching mode. When there are many possible cases, the switch statement is usually used to replace the if statement.
The simplest form of a switch statement is to compare a value with one or more values of the same type:
switch `some value to consider` {case `value 1`: `respond to value 1`case `value 2`,`value 3`: `respond to value 2 or 3`default: `otherwise, do something else`}
The switch statement consists of multiple cases. To match certain more specific values, swift provides several more complex matching modes that will be mentioned later in this section.
Each case is a branch of code execution, which is similar to the IF statement. The switch statement determines which branch should be executed.
The switch statement must be complete. This means that each possible value must have at least one case branch corresponding to it. If it is impossible to cover all values, you can use the default branch to meet this requirement. The default branch must be at the end of the switch statement.
The following example uses the switch statement to match a lowercase character named somecharacter:
Let somecharacter: character = "E" Switch somecharacter {Case "A", "E", "I", "O", "U": println ("\ (somecharacter) is a vowel ") Case" B "," C "," D "," F "," g "," H "," J "," K ", "L", "M", "n", "P", "Q", "r", "S", "T", "V", "W ", "X", "Y", "Z": println ("\ (somecharacter) is a consonant") Default: println ("\ (somecharacter) is not a vowel or a consonant ")} // output" E is avowel"
In this example, the first case Branch is used to match five vowels, and the second case Branch is used to match all consonants.
It is meaningless to write case branches for other possible characters, therefore, the default branch is used in this example to process the remaining non-vowels and non-Consonants-this ensures the completeness of the switch statement.
No implicit penetration (no implicit fallthrough)
Unlike the switch statement in C and objective-C, in swift, when the code in the matching case Branch is executed, the program terminates the switch statement, instead of continuing to execute the next case Branch. This means that you do not need to explicitly use the break statement in the case Branch. This makes the switch statement safer and easier to use, and avoids errors caused by forgetting to write the break statement.
Note:
You can still jump out before the code in the case Branch is executed. For details, see break in the switch statement.
Each case branch must contain at least one statement. Code writing as follows is invalid because the first case Branch is empty:
let anotherCharacter: Character ="a"switch anotherCharacter {case "a":case "A": println("The letter A")default: println("Not the letter A")}// this will report a compile-time error
Unlike switch statements in C, switch statements in swift do not match "A" and "A" at the same time ". On the contrary, the above Code will cause a compilation error: Case "A": does not contain any executable statements -- This avoids accidental penetration from one case Branch to another, makes the code safer and more intuitive.
A case can also contain multiple modes and separate them with commas (, if it is too long, it can be written by branch ):
switch `some value to consider` {case `value 1`,`value 2`: `statements`}
Note: To run through a specific case Branch, use the fallthrough statement. For details, see fallthrough ).
Range matching)
The case branch mode can also be a value range. The following example shows how to use interval matching to output the natural language format corresponding to any number:
Let COUNT = 3_000_000_000_000let countedthings = "stars in themilky 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 ). ") // output" There aremillions and millions of stars in the Milky Way."
Tuple)
You can use tuples to test multiple values in the same switch statement. The elements in the tuples can be values or intervals. In addition, underlines (_) are used to match all possible values.
The following example shows how to use a (INT, INT) type tuples to classify vertices (x, y ):
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 thebox ")} // output" (1, 1) isinside the box"
In the preceding example, the switch statement checks whether a vertex is the origin (0, 0), whether it is on the red X axis, or on the yellow Y axis, whether it is in a 4x4 rectangle centered on the origin or outside the rectangle.
Unlike C, swift allows multiple cases to match the same value. In this example, vertices (0, 0) can match all four cases. However, if there are multiple matches, only the first matched case Branch will be executed. Considering that (0, 0) first matches case (0, 0), the remaining case branches that can match (0, 0) will be ignored.
Value bindings)
The case branch mode allows matching values to be bound to a temporary constant or variable, these constants or variables can be referenced in the case Branch-this behavior is called value binding ).
The following example shows how to use value binding in a (INT, INT) type tuples to classify vertices (x, y ):
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)")} // output "on thex-axis with an X value of 2"
In the preceding example, the switch statement checks whether a vertex is on the red X axis, yellow Y axis, or not on the coordinate axis.
All three cases declare placeholders of constants X and Y, which are used to temporarily obtain one or two values of the tuples anotherpoint. The first case -- Case (Let X, 0) matches a point with an ordinate value of 0 and assigns the abscissa of this point to a temporary constant X. Similarly, the second case -- Case (0, let y) will match a point with a abscissa of 0 and assign the ordinate coordinates of the point to the temporary constant y.
Once these temporary constants are declared, they can be referenced in their corresponding case Branch. In this example, they are used to simplify println writing.
Note that this switch statement does not contain the default branch. This is because the last case -- case Let (X, Y) declares a tuples that can match all the remaining values. This makes the switch statement complete, so you do not need to write the default branch.
In the preceding example, X and Y are constants because they do not need to be modified in the corresponding case Branch. However, they can also be variables-the Program will create a temporary variable and initialize it with the corresponding value. Modifying these variables only affects the corresponding case Branch.
Where
In case branch mode, you can use the where statement to determine additional conditions.
In the following example, vertices (x, y) are classified:
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 ")} // output" (1,-1) ISON the Line X =-y"
In the preceding example, the switch statement checks whether a vertex is on the green diagonal line x = Y, whether it is on the purple diagonal line x =-y, or not on the diagonal line.
All three cases declare placeholders of constants X and Y, which are used to temporarily obtain two values of the tuples yetanotherpoint. These constants are used as part of the where statement to create a dynamic filter ). If the where statement is true, the matched case Branch is executed.
As in the example of value binding, the switch statement is complete because the last case Branch matches all the remaining values, so you do not need to write the default branch.