Swift it provides a similar C traffic control architecture language, which contains the ability to run multiple tasks for and while cycles. Choose to run the IF and switch declarations according to the specific conditions of the different coded branch offices, with the control flow jumping to other code break and continue declarations.
In addition to the C language inside the traditional for conditional increment (for-condition-increment) loop. Swift also adds a for-in loop. To make it easier to repeat the group (array). Dictionary (dictionary), interval (range), string, and other sequence types.
Swift's switch statement is more powerful than the C language. In C, suppose that a case accidentally misses a break, and it runs through (Fallthrough) to the next. Swift does not have to write a break, so this is not happening in the run-through (Fallthrough) situation. Case can also match many other types of patterns. Contains interval matching (range matching). Tuple and descriptive narrative of a particular type. The matching value in a case statement of switch can be determined by a temporary constant or variable within the case body, or a more complex match condition can be described by the WHERE clause.
For loop
The For loop is used to run a series of statements several times, as specified. Swift offers two kinds of for loop form:
The for-in is used to traverse a range (range). Sequence (sequence). Set (collection), all elements of the series (progression) run a series of statements.
The For Condition Increment (for-condition-increment) statement. Used to run a series of statements repeatedly until a specific condition is reached. This is typically done by adding a counter value after each loop is completed.
For-in
You can use the for-in loop to iterate through all the elements in a collection, such as the interval represented by a number, the elements in an array, and the characters in a string.
The following sample is used to output the preceding part of the Multiply 5 table:
For index in 1...5 { println ("\ (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 element used to traverse in the sample is a set of using the Closed interval operator (...). ) represents a number from 1 to 5. Index is assigned the first number in the closed interval (1), and the statement in the loop is run once.
In this case, the loop consists of just one statement. Used to output the result of the Multiply 5 multiplication table corresponding to the current index value. After the statement is run, the value of index is updated to the second number in the closed interval (2). The Println method is then run again.
The entire process is reached until the end of the closed interval.
In the example above. Index is a constant that is actively assigned to each iteration of the loop at the beginning. Such a case. Index is not required to be declared before use. It is only necessary to include it in the declaration of the Loop. It can be implicitly declared without the use of the Letkeyword declaration.
Attention:
The index constant exists only in the life cycle of the cycle. Suppose you want to access the value of index after the loop is complete, or if you want index to be a variable instead of a constant, you must declare it yourself before the loop.
Suppose you don't need to know the value of each item in the interval. You can use the underscore (_) to override the variable name to ignore the access to the value:
Let base = 3let Power = 10var Answer = 1for _ in 1...power { answer *= base}println ("\ (base) to the power of\ (power) I s \ (Answer) ")//Output" 3 to Thepower of 59049 "
This example calculates the power sub-power of this number of base (in this case. is 3 of the power of 10), starting from 1 (3 of the power of 0) to do 3 multiplication, 10 times. Use a half-closed interval loop of 0 to 9. This calculation does not need to know the detailed value of the counter in each cycle, just need to run the correct number of cycles. The underscore symbol _ (the variable in the substitution loop) ignores the detailed value and does not provide access to the value when looping through.
Use for-in to iterate through an array of all elements:
Let names = ["Anna", "Alex", "Brian", "Jack"]for name in Names { println ("Hello, \ (name)!")} Hello, anna!//hello, alex!//hello, brian!//hello, jack!
You can also access its key-value pairs (Key-value pairs) by traversing a dictionary. As you traverse the dictionary, each element of the dictionary is returned as a (key, value) tuple, and you can use an explicit constant name in the for-in loop to interpret (key, value) tuples. In the following example. The dictionary's key (key) is interpreted as a constant animalname, and the value of the dictionary is interpreted as a constant legcount:
Let Numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]for (Animalname, Legcount) in numberoflegs{ println ("\ (animalname) S has \ (legcount) legs ")}//spiders has 8 legs//ants has 6 legs//cats have 4 legs
The traversal order and Insertion Order of the dictionary elements may be different. The contents of the dictionary are unordered internally, so the order is not guaranteed when traversing elements. For arrays and dictionaries, see the collection type for details.
In addition to arrays and dictionaries, you can also use the for-in loop to iterate through the characters in a string (Character):
For character in "Hello" { println (character)}//h//e//l//l//o
For condition Increment (for-condition-increment)
In addition to the for-in Loop, Swift provides a standard C-style for loop that uses conditional inference and incrementing methods:
for var index = 0; Index < 3; ++index { println ("index")}//index is 0//index was 1//index is 2
The following are the usual formats for looping in this way:
For ' initialization '; ' Condition '; ' increment ' { ' statements '}
As in C, a semicolon divides the definition of a loop into 3 parts. The difference is. Swift does not need to use parentheses to "initialization; Condition Increment "included.
This cycle runs the following processes such as:
When the loop is first started. Initialization expressions (initialization expression) are called once to initialize all the constants and variables required by the loop.
Conditional expressions (condition expression) are called. Suppose the expression invokes the result of false, the loop ends, and the code continues after the for loop closes the curly brace (}). Assume that the expression invocation result is true. The code inside the curly braces (statements) is run.
After running all statements (statements), run an increment expression (increment expressions).
The value of the counter is generally added or lowered. or alter an initialized variable by the output of the statement (statements). When the increment expression finishes running, the 2nd step is run repeatedly, and the conditional expression runs again.
The descriptive narrative and circular format described above are equivalent to:
' Initialization ' while ' condition ' { ' statements ' increment '}
Constants and variables declared in an initialization expression (such as var index = 0) are only valid for the life cycle of a For loop. Assuming that you want to access the value of index at the end of the loop, you must declare index before the cycle life cycle begins.
var index:intfor index = 0; Index < 3; ++index { println ("index")}//index is 0//index was 1//index is 2println ("The Loop statements Wereexecute d \ (index) times "//Output" The loopstatements were executed 3 times
Note that index finally has a value of 3 instead of 2 after the end of the loop.
The last call to increment expression ++index will set index to 3. This causes the index < 3 condition to be false and terminates the loop.
While loop
The while loop executes a series of statements until the condition becomes false. This type of loop is suitable for use in cases where the number of iterations before the first iteration is unknown.
Swift provides two form of while loop:
While loop. Each time the cycle starts, the calculation conditions are met;
Do-while cycle. Calculates whether the condition meets at the end of the loop.
While
While loops start with the calculation of a single condition. Assuming that the condition is true, a series of statements is executed repeatedly. Until the condition becomes false.
The following is the normal case of the while loop format:
While ' condition ' { ' statements '}
The following example plays a small game called Snakes and Ladders (Snakes and Ladders). Also called a chute and a ladder (Chutes and Ladders):
The rules of the game are as follows:
The game panel contains 25 squares with the goal of reaching or exceeding the 25th square.
Each round, you can determine the number of steps you want to move a block by throwing a 6-sided dice. The moving route is seen by the middle horizontal dashed line;
Suppose at the end of a round. You move to the bottom of the ladder. Be able to climb up the ladder;
Suppose that at the end of a round you move to the head of a snake and you slide down the snake's body.
The game surface can be expressed using an int array. The length of the array is stored by a Finalsquare constant, used to initialize the array and to detect the condition of the victory finally. The game surface is initialized by 26 Int 0 values instead of 25 (from 0 to 25. Altogether 26):
Let Finalsquare = 25var board = int[] (count:finalsquare + 1,repeatedvalue:0)
Some blocks are set to have a specified value for a snake or ladder.
The block at the bottom of the ladder is a positive value. Allows you to move up. The block at the head of the snake is a negative value. Will let you move down:
BOARD[03] = +08; BOARD[06] = +11; Board[09]= +09; BOARD[10] = +02board[14] =-10; BOARD[19] =-11; Board[22]=-02; BOARD[24] = 08
Block 3rd is the bottom of the ladder and will let you move up to number 11th, we use board[03] equals +08 (to represent the difference between 11 and 3).
The unary plus operator (+i) is used in order to be symmetric with the unary minus operator (-i), in order to make the disk face code neat, the number less than 10 is 0 padded (these stylistic adjustments are not required.) Just to make the code look neater).
The player starts the game with a grid numbered 0 in the lower left corner. In general, players will not enter the game disc until the first time they roll the dice:
var square = 0var Diceroll = 0while Square < Finalsquare { //Roll dice if ++diceroll = = 7 {diceroll = 1} /per Points Move Square + = Diceroll If square < Board.count { //Assume the player is still on the board. Climb up the ladder or slide down the snake. square + = Board[square] }}println ("Game over!")
In this example, the simplest method is used to simulate the roll of the dice. The value of Diceroll is not a random number, but an initial value of 0, followed by each while loop, the value of Diceroll is used by the predecessor increment operator (++i) from 1. It then detects if the maximum value is exceeded.
After the ++diceroll call is complete, the return value equals the value of the diceroll increment. Whenever you assume that the value of Diceroll equals 7 o'clock, it exceeds the maximum value of the dice and is reset to 1.
So the order of Diceroll values is always 1,2,3,4,5,6,1,2.
After throwing the dice. The player moves forward diceroll a square, assuming the player moves beyond the 25th square. This time the game is over, corresponding to. The code will move forward or backward (when the ladder or snake is encountered) before the value of square add board[square], and the value of square is less than the Count property of board.
Suppose there is no such test (square < Board.count). Board[square] may have crossed the board array, resulting in an error. For example, assuming that square is equal to 26, the code tries to access board[26], exceeding the length of the array.
When this round of while loop is completed, the loop condition will be checked again to see if the loop needs to be executed again.
If a player moves to or exceeds the 25th square, the loop condition results in false. At this point the game is over.
The while loop is better suited to this case in this case. Because at the start of the while loop, we don't know the length of the game or the number of loops, only the loop will end when the specified condition is reached.
Do-while
The second form of the while loop is do-while, and the difference between it and while is that before the loop condition is inferred, the code block of the loop is run first, and then the loop is repeated until the condition is false.
The following is the format of the Do-while loop under normal circumstances:
Do { ' statements '} and ' condition '
Or a game of snakes and ladders, using the Do-while loop instead of the while loop.
The values of Finalsquare, board, Square, and Diceroll are initialized with the same while loop:
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
Do-while, the first step in the loop is to check whether it is on a ladder or a snake block. No ladder will allow the player to go directly to the 25th square, so the player will not win the game directly through a ladder. It is safe to detect whether stepping on a ladder or a snake at the beginning of a cycle.
When the game starts. The player is on the No. 0 square. BOARD[0] has been equal to 0, will not have any effect:
do { //climb up the ladder or slide down the snake square + = Board[square] //Dice if ++diceroll = = 7 {diceroll = 1} //by points move
square + = Diceroll} while square < Finalsquareprintln ("Game over!")
After checking whether the player has stepped on a ladder or a snake, he starts to roll the dice. The player then moves forward diceroll a square. The end of this round cycle.
The Loop bar item (while square < finalsquare) is the same as while. But it will be calculated only after the loop has ended.
In this game, do-while performance is superior to while better circulation. Do-while this inferred condition that square has no direct execution square + = Board[square] In this way, the version number of the while array boundary inference can be removed in such a manner.
Swift programming language learning 4.1--cycle