The Swift tutorial's control flow detailed _swift

Source: Internet
Author: User
Tags case statement terminates


Swift provides a similar control flow structure in all C languages. Includes for and while loops; if and switch conditional statements, break and continue jump statements, and so on.



Swift also joins the for-in Loop statement, making it easier for programmers to traverse arrays, dictionaries, scopes, strings, or other sequences.



In contrast to the C language, the case statement of the switch statement in Swift does not automatically jump to the next statement, thus avoiding the error caused by forgetting the break in C language. In addition, case statements can match a variety of types, including data ranges, tuples, or specific types. The matching values in the switch statement can also be used in subsequent case statement bodies, where the keyword can be added to any case statement to increase the pattern of the match.



1, for Loop



The For loop can repeatedly execute a code block multiple times, depending on the settings. There are two types of for loops in Swift:
For-in loops, for each element in a data range, sequence, collection, and so on, executes once
For-condition-increment, always executing, knowing that a particular condition is met, each time the loop executes, will increase the count once



For-in Cycle



The following example prints out the top 5 of the multiple sequence of 5





 code as follows:

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





The iteration project is a sequence of numbers, from 1 to 5 closed intervals, by using (...) to represent the sequence. Index is assigned a value of 1, and then executes the code in the loop body. In this case, the loop has only one statement, which is to print the index multiple of 5. After this statement has been executed, the value of index is updated to the next value in the sequence 2,println function is called again, looping until the end of the sequence.



In the example above, index is assigned before each loop starts, so it does not need to be defined before each use. Each time it is implicitly defined, it is like using a let keyword. Note that index is a constant.



Note: Index only exists in the loop, and you need to redefine it if you want to continue using it after the loop is complete.



If you don't need every value in the sequence, you can use _ to ignore it, simply by using the loop body itself:





Copy Code code as follows:

Let base = 3
Let power = 10
var answer = 1
For _ in 1...power {
Answer *= Base
}
println ("\ (base) to the" (answer))
Prints "3 to" 59049 "

This example calculates a specific second side of a number (in this case, 3 of the 10-time side). The continuous multiplication begins at 1 (actually 3 of 0), and then is multiplied by 3, which is performed 0 times due to the use of a half-open interval, from 9 to 10 for the left closing range. There is no need to know the actual execution to the first time in the loop, but to ensure that the correct number of times is performed, so there is no need for the index value.





Similarly, we can use for-in to iterate through the elements of an array.





 code as follows:

Let names = ["Anna", "Alex", "Brian", "Jack"]
For name in Names {
println ("Hello, \ (name)!")
}
Hello, anna!.
Hello, alex!.
Hello, brian!.
Hello, jack!.





When traversing a dictionary, you can use the Key-value pair to traverse. The elements in each dictionary are a (key, value) tuple, and when traversed, the key and value of the field can be specified as a specific name so that they can be better understood and used when traversing, such as Animalname and Legcount in the following example:





 code as follows:

Let Numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]
For (Animalname, Legcount) in Numberoflegs {
println ("\ (animalname) s have \ (legcount) legs")
}
Spiders have 8 legs
Ants have 6 legs
Cats have 4 legs





The elements in the dictionary do not need to be in the order of insertion when traversing, so it is not guaranteed that the elements are orderly when traversing the dictionary. More on the array and dictionary related content can refer to: Collection Types



In addition, similar traversal methods can be used in arrays and dictionaries, such as the use of for-in loops to traverse every character in a string:





 code as follows:

For character in "Hello" {
println (character)
}
H
E
L
L
O





For-condition-increment condition Cycle



Swift also supports the C-style for loop, which also includes a conditional statement and an incremental statement:





code as follows:

for var index = 0; Index < 3; ++index {
println ("index is \ (index)")
}
Index is 0
Index is 1
Index is 2

Here is the general structure for this for loop:







 code as follows:

for initialization; Condition Increment {
Statements
}





The semicolon is used here to separate the three structures of the For loop, as in the C language, but it does not need to be wrapped in parentheses.



This for loop is executed in the following ways:



1. When entering the loop, the initialization statement is executed first, and the variables or constants required by the loop are set.



2, test the conditional statement, see whether the condition of the continuation cycle, only when the conditional statement is true will continue to execute, if False will stop the loop.



3. After all the loop-body statements have been executed, the incremental statement execution may be an increase or decrease in the number of counters, or some other statement. Then return to step 2 to continue execution.



This cyclic approach can also be described as the following form:





 code as follows:

Initialization
While condition {
Statements
Increment
}

Constants and variables that are defined in the initialization statement (such as var index = 0) are valid only within the scope of the FOR Loop statement. If you want to continue using the loop after execution, you need to define it before the loop starts:







 code as follows:

var index:int
for index = 0; Index < 3; ++index {
println ("index is \ (index)")
}
Index is 0
Index is 1
Index is 2
println ("The loop statements were executed \ (index) times")
Prints "The loop statements were executed 3 times"





Note that after the loop completes, the value of index is 3, not 2. Because the index is 1, the conditional statement index < 3 returns false, and the loop terminates, at which point the index is 3.



2, while loop



The while loop executes a series of blocks of code until a condition is false. This cycle is most often used in cases where the number of loops is indeterminate. Swift provides two types of while loops:



While loop, test whether the loop condition is valid before each loop starts



Do-while Loop, test whether the loop condition is set after each cycle



While loop



The while loop starts with a conditional statement and executes if the conditional statement is true until the conditional statement becomes false. The following is a general form of a while loop:





 code as follows:

While condition {
Statements
}





The following example is a simple game, Snakes and ladders, snakes and Ladders:






The rule of the game is this:



The game panel has 25 squares, the goal of the game is to reach the 25th lattice;



Each round through a 6-sided dice to determine the number of steps to walk, the path to walk as shown in the right picture;



If it falls at the bottom of the ladder, climb the ladder and reach the other lattice;



If it falls to the head of the snake, it slips to the square of the snake's tail.



The game panel consists of an array of int, the size of which is set finalsquare by a constant, and is used to detect whether or not a winning lattice has been reached. The game panel is initialized by 26 int number 0 (not 25 because there are 25 digits from 0 to 26)





 code as follows:

Let Finalsquare = 25
var board = int[] (count:finalsquare + 1, repeatedvalue:0)

Some of these lattices are set to certain values to indicate snakes or ladders. The place with the ladder is an integer, and the place with the snake is negative:







 code as follows:

BOARD[03] = +08; BOARD[06] = +11; BOARD[09] = +09; BOARD[10] = +02
BOARD[14] =-10; BOARD[19] =-11; BOARD[22] =-02; BOARD[24] =-08

The third lattice is the bottom of a ladder, indicating that the player can reach the 11th grid through a ladder, so setting board[3] is +08, indicating 8 steps forward. The position of the same snake is set to a negative number, indicating back I step.





The player starts the game from a grid of 0.


 code as follows:

var square = 0
var diceroll = 0
While Square < Finalsquare {
Roll the Dice
if ++diceroll = = 7 {diceroll = 1}
Move by the rolled amount
Square + Diceroll
If square < Board.count {
If we ' re still on the board, move up or down for a snake or a ladder
Square + + Board[square]
}
}
println ("Game over!")





This example uses a very simple way to roll the dice, which is to add 1 each time instead of using a random number. Diceroll used to indicate the number of steps to walk each time, it should be noted that every time before execution, ++diceroll will first execute plus 1, and then compared with 7, if equal to 7, set to 1, so you can see Diceroll change is 1,2,3,4,5,6,1 ...



After the dice is rolled, the player moves the number of steps indicated by the Diceroll, which may have exceeded the finalsquare, so it is necessary to perform an if, if true, the event on the grid: If the normal lattice does not move, if the ladder or the snake moves the corresponding steps, Here you just need to use Square + board[square] directly.



After the while loop completes, re-check whether the square < Finalsquare is set up and continue the game until the game is over.



Do-while Cycle



Another while loop is a do-while loop. In this cycle, the statements in the loop body are executed once, before the detection of the cyclic condition is satisfied, and the following is the general form of the Do-while loop:





 code as follows:

do {
Statements
} while condition





The above snake and ladder game uses the Do-while loop to write can be done this way. The initialization statement and the while loop are similar:





 code as follows:

Let Finalsquare = 25
var board = int[] (count:finalsquare + 1, repeatedvalue:0)
BOARD[03] = +08; BOARD[06] = +11; BOARD[09] = +09; BOARD[10] = +02
BOARD[14] =-10; BOARD[19] =-11; BOARD[22] =-02; BOARD[24] =-08
var square = 0
var diceroll = 0





In this cycle, the first action is to detect whether the ladder or the snake, because there is no ladder or snake can let the player directly to the 25th grid, so the game will not end directly, the next process is similar to the while loop above, the cycle of conditional statements or whether the test has reached the final grid.





 code as follows:

do {
Move up or down for a snake or ladder
Square + + Board[square]
Roll the Dice
if ++diceroll = = 7 {diceroll = 1}
Move by the rolled amount
Square + Diceroll
While Square < Finalsquare
println ("Game over!")





3, conditional statement



In general, we all need to execute different statements according to different conditions. For example, when an error occurs, a statement that executes some error message tells the programmer whether the value is too large or too small. You need to use conditional statements here.



Swift provides two ways to conditionally branch statements, if statements, and switch statements. General if statements are more common, but only a small number of conditions can be detected. A switch statement is used for conditional statements when a large number of conditions may occur.



If statement



In the most basic if statement, the conditional statement has only one, and if the condition is true, execute the statement in the IF statement block:





code as follows:

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

The above example detects whether the temperature is lower than 32 degrees Fahrenheit (32 degrees Fahrenheit is the freezing point of water, and is not the same as Celsius), and if it is low, it outputs a line of statements. If not low, it will not output. An IF statement block is a part that is enclosed in curly braces.





When a conditional statement has multiple possibilities, the Else statement is used, and if false, the Else statement starts executing:





 code as follows:

Temperatureinfahrenheit = 40
If Temperatureinfahrenheit <= 32 {
println ("It" s very cold.) Consider wearing a scarf. ")
} else {
println ("It" isn't that cold.) Wear a T-shirt. ")
}
Prints "It" isn't that cold. Wear a T-shirt. "

In this case, one of the two branches is bound to be executed.





You can also have multiple branches, using multiple if and else





 code as follows:

Temperatureinfahrenheit = 90
If 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. ")
} else {
println ("It" isn't that cold.) Wear a T-shirt. ")
}
Prints "It ' s really warm. Don ' t forget to wear sunscreen. "

In the example above, there are multiple if occurrences to determine whether the temperature is too low or too high, and the last else indicates a time when the temperature is not high or low.





Of course else can also be omitted





 code as follows:

Temperatureinfahrenheit = 72
If 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, no information is entered when the temperature is not high or low.





Switch statement



A switch statement examines the multiple possibilities of a value and compares it with multiple case decisions to determine which branch of code to execute. A switch statement differs from an if statement in that it can also provide multiple instances of a match when a plurality of statement blocks are executed.



The general structure of the switch statement is:





 code as follows:

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
}

Each switch statement contains multiple case statement blocks, and in addition to direct comparison values, Swift provides a variety of more complex pattern matching ways to select the branch of statement execution, which will continue to be introduced in subsequent sections.





In a switch, each case branch is matched and detected, and the default keyword must be used for all cases not mentioned. Note that the default keyword must be at the end of all case.



The following example uses a switch statement to determine the type of a character:





 code as follows:

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")
}
Prints "E is a vowel"

In this example, first look at the character is not a vowel letter, and then detect whether the consonant letter. Other cases are matched by default.





does not always execute



Unlike C and OBJECTIVE-C, the switch statement in Swift does not jump to the next case statement because there is no break at the end of the case statement. The switch statement executes only the statements in the case that match, and then stops directly. This makes the switch statement more secure because programmers often forget to write a break.



Each case requires a statement that can be executed, and the following example is incorrect:





 code as follows:

Let Anothercharacter:character = "a"
Switch Anothercharacter {
Case "a":
Case "A":
println ("The Letter A")
Default
println ("Not the letter A")
}
This'll a compile-time error

Unlike C, a switch statement does not match a and a at the same time, and it complains directly. A case can have multiple conditions, separated by commas:







 code as follows:

Switch some value to consider {
Case value 1,
Value 2:
Statements
}

Range Matching





The case of a switch statement can match a range of values, such as:





 code as follows:

Let count = 3_000_000_000_000
Let countedthings = "stars in the Milky Way"
var naturalcount:string
Switch 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."





META Group



Case can also directly test whether the tuple meets the appropriate conditions, _ can match any value.



The following example is whether the judge (X,y) is in the rectangle, and the tuple type is (Int,int)


Copy Code code as follows:

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"








Unlike the C language, Swift can determine whether a tuple meets the criteria.



Numeric bindings



While case matching, you can bind the value in the switch statement to a specific constant or variable for use in the statement of the case. Like what:





Copy Code code as follows:

Let Anotherpoint = (2, 0)
Switch Anotherpoint {
Case (Let x, 0):
println ("On", 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" X-axis with an X value of 2 "








The switch statement determines whether a point is on the x-axis or the y-axis, or somewhere else. Matching and numeric bindings are used here. In the first case, if the point is (x,0) mode, the value is bound to x so that the value can be output in case statements. Similarly, if you are on the y-axis, you output the value of Y.



where keyword



The switch statement can use the WHERE keyword to increase the condition of the judgment, in the following example:





Copy Code code as follows:

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"








Each case is different because of where it is, and the first case is to determine if x is equal to Y, and the point is on the slash y=x.



4, control the jump statement



There are 4 ways to control jump statements in swift, allowing programmers to better control the flow of code, including:



Continue



Break



Fallthrough



Return



Where Continue,break and Fallthrough are described in detail below, the return statement is described in the function chapter.



Continue



The continue statement tells a loop to stop the statement that is now executing and start the next loop.



Note: In the for-condition-increment loop, the increment increment statement is still executed, but the loop body is skipped.



The following example implements the removal of spaces and vowels in a string to form a crossword puzzle:





Copy Code code as follows:

Let Puzzleinput = "great minds to alike"
var puzzleoutput = ""
For character in Puzzleinput {
Switch character {
Case "A", "E", "I", "O", "U", "":
Continue
Default
Puzzleoutput + + character
}
}
println (Puzzleoutput)
Prints "Grtmndsthnklk"





Each character of the string is traversed, and the next loop is ignored when a vowel or space is encountered, resulting in a final crossword puzzle.



Break



The break statement terminates execution of the entire loop, either in a loop statement or in a switch statement.





Copy Code code as follows:

Let Numbersymbol:character = "three"//Simplified Chinese for the number 3
var possibleintegervalue:int?
Switch Numbersymbol {
Case "1", "١", "One", "๑":
Possibleintegervalue = 1
Case "2", "٢", "Two", "๒":
Possibleintegervalue = 2
Case "3", "٣", "three", "๓":
Possibleintegervalue = 3
Case "4", "٤", "Four", "๔":
Possibleintegervalue = 4
Default
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 above example first checks whether Numbersymbol is a number, Arabic numerals, Chinese characters, Latin, or Swahili. If the match completes, the Possibleintegervalue is assigned a value. Finally, it detects whether the value has been assigned through an if statement and binds it to the IntegerValue constant, the final output. The default statement is used to meet situations where the above case cannot be matched, but there is no need to do anything, so use the break to terminate directly.



Fallthrough



Because the switch statement in Swift does not automatically jump to the next case because there is no break, you need to use the Fallthrough keyword if you want to do it in the C language, and then execute each of the cases sequentially.



As in the following example, the default branch will eventually be executed:





Copy Code code as follows:

Let Integertodescribe = 5
var description = "The number \ (Integertodescribe) is"
Switch Integertodescribe {
Case 2, 3, 5, 7, 11, 13, 17, 19:
Description = "A prime number, and also"
Fallthrough
Default
Description + = "an integer."
}
println (description)
Prints "The number 5 is a prime number, and also an integer."





Label statement



Switch and loops can be nested, and loops can be nested between each other, so when you use a break or continue, you need to know exactly which statement is working. This requires that you use a label statement. The general form of the label statement is as follows:





Copy Code code as follows:

Label Name:while Condition {
Statements
}

The following example shows how to use label statements and nested loops and switch.





Still using the previous ladder and the Snake game, the first step is still set the initial value:





Copy Code code as follows:

Let Finalsquare = 25
var board = int[] (count:finalsquare + 1, repeatedvalue:0)
BOARD[03] = +08; BOARD[06] = +11; BOARD[09] = +09; BOARD[10] = +02
BOARD[14] =-10; BOARD[19] =-11; BOARD[22] =-02; BOARD[24] =-08
var square = 0
var diceroll = 0





Then, use a while loop to complete the game with the switch nesting





Copy Code code as follows:

Gameloop:while Square!= Finalsquare {
if ++diceroll = = 7 {diceroll = 1}
Switch Square + diceroll {
Case Finalsquare:
Diceroll'll move us to the final square, and so the game are over
Break Gameloop
Case let Newsquare where Newsquare > Finalsquare:
Diceroll'll 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!")





In this code, the cycle of the game is named Gameloop, and then in each step move the grid, to determine whether the current end of the game, in the break, you need to end the entire game cycle, rather than terminate the switch, so use the break gameloop. Similarly, in the second branch, continue Gameloop also indicates that the whole game needs to be continue, not the switch statement itself.


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.