swift--Control Flow

Source: Internet
Author: User
Tags case statement switch case

Tag: Desc ACK Stride not value exists to jump out of loop pil cond

Swift provides a series of control states, including a while loop that can perform the same task multiple times, statements such as if guard switch that perform different branches depending on different conditions, and, for example, break and continue to choose whether to jump out of the loop to execute additional code.

Swift also provides a way to quickly traverse arrays, dictionaries, scopes, strings, and so on: for-in loops.

Swift statements in Swift are more powerful than functions similar to those in C, and case statements can be adapted to many different types, such as interval matching, tuples, or a particular type. In a switch case, a matching value can be bound to a temporary constant or variable, used in the body of a case, and a complex match condition can be represented by a WHERE clause.

1. For-in Cycle

You can use for-in to iterate through an array, a dictionary, a character in a string, and so on.

Let names = ["Anna", "Alex", "Brian", "Jack"]for the name in names {    print ("Hello, \ (name)!")} Hello, anna!//hello, alex!//hello, brian!//hello, jack!

You can use for-in to iterate through the dictionary to get the key-value pairs in the dictionary. Each item in the dictionary is returned as a tuple type (key,value);

Let Numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]for (Animalname, Legcount) in Numberoflegs {    print ("\ (animalname) s has \ (legcount) legs ")}//ants has 6 legs//spiders has 8 legs//cats have 4 legs

The elements in the dictionary are unordered, and the data traversing the dictionary is not guaranteed to be sequential. Usually you insert a new value sequentially, and the dictionary does not traverse sequentially.

You can also use the for-in loop to iterate through the range of values.

For index in 1...5 {    print ("\ (index) times 5 are \ (Index * 5)")}//1 times 5 is 5//2 times 5 are 10//3 times 5 is 15// 4 times 5 is 20//5 times 5 is 25

The traversed sequence is a range of numbers from 1 to 5, including the use of the Closed-field operator (...). Set the index value to the first number in range (1) and execute the statement in the loop. In this case, the loop contains only one statement, which outputs the entry of the current index value from a table of 5 times times. After executing the statement, the value of index is updated to contain the second value in range (2), and the print (_: delimiter: Terminator:) function is called again. The process continues until it reaches the end of the distance.

In the example above, index is a constant whose value is set automatically at the beginning of each iteration of the loop. Therefore, the index does not need to be declared before use. It is implicitly declared as simply contained in a circular declaration, without requiring a let declaration keyword.

If you do not need to get each value from the sequence, you can use an underscore instead of the variable name to ignore the value.

Let base = 3let Power = 10var Answer = 1for _ in 1...power {    answer *= base}print ("\ (base) to the power of \ (Power) is \ (Answer) "//Prints" 3 to the power of 59049 "

In some cases, you may not want to close the interval (including the values on both sides). Consider drawing a minute stopwatch tick value on the dial, if you want to draw 60, you need to start with 0, use the semi-open difference operator (. <)--contains the minimum value, but does not contain the maximum value.

Let minutes = 60for Tickmark in 0..<minutes {    //render the tick mark each minute)}

Some users want their interface to have fewer ticks, they may tick 5 seconds. Use the STRIDE (From:to:by:) method to skip the unwanted tick values.

Let Minuteinterval = 5for Tickmark in stride (from:0, to:minutes, by:minuteinterval) {    //render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)}

Closed intervals can also be replaced with stride (From:through:by):

Let hours = 12let Hourinterval = 3for Tickmark in stride (From:3, through:hours, by:hourinterval) {    //render the TI CK Mark every 3 hours (3, 6, 9, 12)}

2. While loop

The while loop begins by judging whether the condition is met, and if the condition satisfies, executes the while internal code, knowing that its condition is not satisfied.

While condition {    statements}

3.rapeat-while Cycle

The Repeat-while loop is another version of the while loop. If the condition is satisfied, the code inside the loop is executed first, and if the condition is not satisfied, the loop is resumed and the loop is known to meet the condition.

Repeat {    statements} while condition

4. Conditional control Statements

It is common to execute different code for different conditions. When an error occurs, you may need to execute a different code or display a hint when a value is too high or too low. To achieve this effect, let your part of the code become a conditional statement.

Swift provides two ways to add conditional branching in code: The IF statement and the switch statement. Usually, you use the IF statement to judge a simple sentence with only a few possible sentences; switch is useful for judging the complexity of some values that are more complex and for choosing different execution codes for matching different conditions.

(1) if

In the most recent simple form, the IF statement has only one simple if condition. When the condition is true, the code inside the if is executed.

var Temperatureinfahrenheit = 30if Temperatureinfahrenheit <= {    print ("It's very cold. Consider wearing a scarf. ")} Prints "It ' s very cold. Consider wearing a scarf. "

The IF statement can provide another set of statements, called the ELSE clause, for cases where the condition is false. These statements are represented by the Else keyword.

Temperatureinfahrenheit = 40if Temperatureinfahrenheit <= {    print ("It's very cold. Consider wearing a scarf. ")} else {    print ("It ' s not so cold. Wear a T-shirt. ")} Prints "It ' s not so cold. Wear a T-shirt. "

You can use multiple if statements overlay, you can consider the additional words;

Temperatureinfahrenheit = 90if Temperatureinfahrenheit <= {    print ("It's very cold. Consider wearing a scarf. ")} else if Temperatureinfahrenheit >=, {    print ("It's really warm. Don ' t forget to wear sunscreen. ")} else {    print ("It ' s not so cold. Wear a T-shirt. ")} Prints "It ' s really warm. Don ' t forget to wear sunscreen. "

(2) switch

A switch statement can be thought of as a process that matches a value to multiple possible values. When a value match succeeds, the corresponding block of code is executed to provide another option for responding to multiple optional if statements.

In Swith simple format, a switch statement compares a value to one or more values of the same type:

Switch some value to consider {case value 1:    respond to value 1case value 2,     value 3:    respond to value 2 or 3d Efault:    Otherwise, do something else}

Each switch statement consists of multiple case statements, with each case statement starting with the case keyword. In addition to comparing the specified values, Swift also provides several methods for matching complex case statements.

Similar to the IF statement, the branch of each case statement is separated by the code executed. The switch statement determines which branch to select.

Each switch statement should be verbose. The type of each possible value should conform to the type of one of the case in the switch statement. If it is not appropriate to provide a case statement for all possible values, you can set a default statement to contain any ambiguous values. This default statement is declared with the default keyword and must appear at the end.

Let somecharacter:character = ' z ' switch somecharacter {case ' a ': print ("The first letter of the    alphabet") case "Z": 
   print ("The last letter of the alphabet") Default:    print (' Some other character ')}//Prints "The last letter of the AL Phabet "

Unlike the switch in C or OC, in Swift, the switch statement does not automatically enter the next case statement. Conversely, a case statement that does not need to be explicitly written break,switch will end once the switch statement conforms to one of the story statements and executes the code. The switch statement in C is more secure, easier to use, and easier to avoid errors.

There should be at least one execution code under each case statement, as the following code is invalid because the first case is empty:

Let Anothercharacter:character = ' A ' switch anothercharacter {case ' a '://Invalid, the case had an empty Bodycase "a": 
   print ("The Letter A") Default:    print (' Not the letter a ')}//this would report a compile-time error.

Inconsistent with the C switch statement, this switch statement does not satisfy both the "a" and "B" cases. At the same time, it will report a compile-time error in the case "a" statement: Case "A" does not contain any code for execution. This approach avoids accidental occurrences from a case condition, into the next condition, and makes the code more secure and more explicit.

To implement a case statement that conforms to "a" and "a", separate the two values in the same compound case statement with ",".

Let Anothercharacter:character = ' A ' switch anothercharacter {case ' a ', ' a ':    print ("The letter A") Default:    Print ("Not the Letter A")} Prints "The Letter A"

For readability, a conforming statement can be written in multiple lines.

(1) Interval matching

The value of case in Swift can be checked out in the interval, as in the example below, which uses a numeric interval to provide a natural language count for numbers of any size:

Let Approximatecount = 62let countedthings = "moons orbiting Saturn" let Naturalcount:stringswitch approximatecount {case 0:    naturalcount = "No" case 1..<5:    naturalcount = ' A few ' case 5..<12:    naturalcount = ' several ' case 12. <100:    naturalcount = "Dozens of" case 100..<1000:    naturalcount = "hundreds of" default:    Naturalcount = "Many"}print ("there is \ (Naturalcount) \ (countedthings).") Prints "There is dozens of moons orbiting Saturn."

(2) Meta-group

You can use tuples to test whether multiple values in the Swith statement are the same. The elements of each tuple are tested according to different values or different interval values. Or you can use "_" to match all possible values.

For example, the points for (x, y) are represented by a tuple (int, int) Type:

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

(3) where

You can use the WHERE clause to check for additional conditions in the switch statement, as in the following example:

Let Yetanotherpoint = (1,-1) switch yetanotherpoint (x, y) where x = = y:    print ("(\ (x), \ (y) x = = y ") case let (x, y) where x = = y:    print (" (\ (x), \ (y)) is on the line x = =-Y ") case let (x, y):    print (" (\ (x), \ (y)) is just some arbitrary point ")}//Prints" (1,-1) are on the line x = = y "

(4) Complex statements

Switch multiple case if the code in the case is the same, you can write two conditions in the same scenario statement, with each condition separated by the "," number. If there is any one condition satisfied it is considered that this case condition is satisfied. If this condition statement is too long, it can be displayed with multiple lines:

Let Somecharacter:character = "E" switch somecharacter {case "a", "E", "I", "O", "U":    print ("\ (Somecharacter) is a vow El ") case" B "," C "," D "," F "," G "," H "," J "," K "," L "," M ","     n "," P "," Q "," R "," s "," T "," V "," w "," X "," Y "," Z ":    Print ("\ (somecharacter) is a consonant") Default:    print ("\ (Somecharacter) are not a vowel or a consonant")}//Prints "E is a vowel "

The first example of a switch statement matches all five lowercase vowels in English. Similarly, it matches all lowercase English consonants in the second case. Finally, the default matches any other character.

Compound statements can also include value bindings. All patterns of a compound statement must contain the same set of value bindings, and each binding must obtain a value of the same type from all patterns in the compound statement. This ensures that, regardless of which part of the compound statement matches, the code in the case body can always access the bound value, and the value always has the same type.

5. Control transfer Statements

Control transfer statements can change the order in which your code executes, by controlling the transfer statements from one block of code to another block of code. Swift has 5 control of 5 transfer statements:

Contitue

Break

Fallthrough

Return

Throw

This chapter describes only the previous three control transfer statements.

(1) Continue

Continue this statement is to tell the loop to end the current code execution and start the next loop again. The equivalent of saying: "has been repeating the current loop", did not leave this loop.

The next example is to delete the vowel letters in a lowercase string into a new string:

Let Puzzleinput = "great minds think alike" var puzzleoutput = "Let characterstoremove: [Character] = [" A "," E "," I "," O ", "U", "" "]for character in Puzzleinput {    if Characterstoremove.contains (character) {        continue    } else {        PU Zzleoutput.append (character)    }}print (puzzleoutput)//Prints "Grtmndsthnklk"

(2) Break

The break statement can immediately end execution of the code block. The break statement can be used within a switch or loop statement, when you want to end the execution of the code prematurely.

Using break in a loop statement

When you use break in a loop statement, break immediately ends the current loop code and jumps out of the loop to execute code outside the "}". The current loop code is no longer executed and does not restart a new round of loops.

Break in a switch statement

When break is used in a switch branch, the use of break can immediately execute code within the technology switch branch and execute code outside of switch and switch "}".

This behavior can be used in matching or ignoring switch statements. Because the Swith statement in Swift is exhaustive and does not allow empty blocks of code in the case statement, it is necessary for you to have a clearer idea of how to match or omit some case statements. When you execute a case statement in which a compound is executed in a switch, the current switch code is terminated immediately when a break is executed to break.

Let Numbersymbol:character = "three"  //Chinese symbol for the number 3var Possibleintegervalue:int?switch Numbersymbol {case "1", "?", "One", "?":    Possibleintegervalue = 1case "2", "?", "Two", "?":    Possibleintegervalue = 2case "3", "?", "Three", "?":    Possibleintegervalue = 3case "4", "?", "Four", "?":    Possibleintegervalue = 4default:    break}if let inte Gervalue = possibleintegervalue {    print ("the integer value of \ (Numbersymbol) is \ (IntegerValue).")} else {    print ("An integer value could not being found for \ (Numbersymbol).")} Prints "The integer value of three is 3."

(3) Fallthrough

When each case in the Swift,swift statement does not end, it is automatically entered into the next cases statement, and the switch statement is fully executed when the condition is met. Conversely, in the C language, it is explicitly necessary to insert a break after the case statement ends and to prevent the entry of the next cases statement from this one. Avoiding the default execution of Fallthrough means that the switch statement in Swift is more consistent and predictable than in C, so that you can avoid executing multiple switch statements incorrectly.

If you need a C-type Fallthrough behavior, you can choose between case and Fallthrough keyword.

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

Note: When FALLTHROUHT critical use, the condition of the next case statement is not judged, but instead goes directly to the code block that executes the next case statement.

6. Label declaration

In SWITF, you might nest a loop and conditional statement in a looping statement to generate a complex control condition statement. However, loops and conditional statements can use break to end their execution. Therefore, it is sometimes useful to end the code in a loop statement with a break statement. Similarly, if there are multiple nested loop statements, continue in the Loop statement is also very effective.

To achieve this goal, you can tag a loop statement or conditional statement with a tag statement. Using a conditional statement, you can use the break statement to end the execution of a tag statement in a statement label. In a looping statement, you can either end or continue marking the execution of a statement with a break or continue statement in a tag statement.

The declaration format for a label statement is as follows: The name of the tag is separated by ":" Before the statement.

(label name): While condition {    statements}//() does not have to be written, this is written in order to prompt the name of the whole, not the label + name

Examples are as follows:

Gameloop:while Square! = finalsquare {    Diceroll + = 1    if Diceroll = = 7 {diceroll = 1}    switch Square + Dicero ll {case    Finalsquare:        //Diceroll'll move us to the final square, so the game was over break        Gameloop    CA Se let newsquare where Newsquare > Finalsquare:        //Diceroll'll move us beyond the final square, so roll again
   
    continue gameloop    Default:        //This was a valid move, so find out its effect        square + diceroll        Square + = Board[square]    }}print ("Game over!")
   

Note: If the break statement is used without the gameloop tag, then break jumps out of the switch statement instead of the while loop.

6. Early exit

A guard statement is similar to an if statement and is judged by the Boolean value returned by an expression. The guard statement must be judged to be true when the code behind the guard is executed with the Gurad statement. Inconsistent with the IF statement, the Else statement in the guard statement is always present, and when the condition is not met, the case statement executes.

Func Greet (person: [string:string]) {    guard-let name = person["name"] else {        return    }        print ("Hello \ (nam e)! ")        Guard Let location = person[' Location '] else {        print ("I hope the weather is nice near you.")        Return    }        print ("I hope the weather is nice in \")} Greet (person: ["name": "John"])//Prints "Hello John !" Prints "I hope the weather is nice near you." Greet (person: ["name": "Jane", "Location": "Cupertino"])//Prints "Hello jane!" Prints "I hope the weather is nice in Cupertino."

If the conditions in the guard statement are met, the code outside the guard is executed. Any variable or constant declared in the condition judgment of the guard statement can be used in code other than guard.

If the condition is not met, the code branch outside of codes is executed. In the case branch, you must let the code end execution. You can use break,return,continue, throw to achieve.

7. Check the feasibility of the API

Swift's compilation is done by checking the API to make sure that you don't actually invoke an API that is not available in the actual execution of the task.

The compiler will use the SDK's useful information to check all the APIs your application uses in your code. When you use an unavailable API, Swift prompts for compile-time error messages.

You can use the availability condition in the If or guard statement to determine whether the API you want to run in runtime is valid, to conditionally execute blocks of code. When the check API is valid in code, the compiler uses the conditional information for these possibilities.

If #available (iOS, MacOS 10.12, *) {    //use iOS ten APIs on IOS, and use MacOS 10.12 APIs on MacOS} else {    //Fa ll back to earlier IOS and MacOS APIs}

The above availability criteria are specified in iOS, where the body of the IF statement is executed only in IOS10; in MacOS, only after MacOS 10.12 and later. The last parameter, * is required, and is specified on any other platform if the target specifies the minimum deployment target.

In its general form, the availability condition contains a list of platform names and versions. You can use platform names (such as iOS, MacOS, watchOS, and tvOS) as a complete list, see declaring properties. In addition to specifying a major version number, such as iOS 8 or MacOS 10.10, you can also specify a smaller version number, such as ios8.3 and MacOS 10.10.3.

If #available (platform name version, ..., *) {statements to    execute if the APIs is available} else {    fallback St Atements to execute if the APIs is unavailable}

swift--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.