7.Swift Translation Tutorial Series-The process of controlling loops

Source: Internet
Author: User
Tags case statement

English pdf download link http://download.csdn.net/detail/tsingheng/7480427

Swift provides a similar C-language control flow structure. Contains a for loop and a while loop to run the task multiple times, and the IF and switch statements run different branch codes according to different conditions, and the break and continue statements jump the run process to other statements.

In addition to the traditional for-condition in C-increment cycle. Swift also adds a for-in loop to iterate through the array. Dictionaries, ranges, strings, or other sequences are very easy.

Swift's switch statement is also more powerful than the C-language switch.

A case statement in Swift will not run after it has run out of the following case. Avoid errors caused by forgetting to write break in C.

A case can match many different types of patterns, including range matching, tuples, or a specific type (casts to a specific type).

case where a matched value can be bound to a temporary constant or variable to be used in a case, a complex match condition can be represented by a where.

1.for Cycle

The For loop repeats the number of times the statement is run.

Swift provides two types of for loops:

    • For-in in a range, sequence. A collection or series that runs once for each element.

    • The for-condition-increment repeats until a particular condition is met, typically incrementing the counter after each cycle.

For-in

You can use the for-in loop to iterate through the elements of a collection, such as a range of numbers, an element in an array, or a character in a string.

The following example outputs the row in the multiplication table that is multiplied by 5:

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 collection of elements to traverse is used ... Creates a closed interval of 1 to 5. The value of index is set to the first value of the range of 1, and the statement in the loop body is run. In this example, the loop body consists of only one statement. is the output multiplication table. After the statement has finished running. The value of index is updated with the second value of the range, 2, and the output statement is run again. This process has been the last value of the range.

The above qualifications. Index is a constant and is assigned on its own initiative each time a loop is made. In such a case, index does not need to be declared before use.

In for-in, the direct use of index is equivalent to implicitly declaring the constant index, no need to use Letkeyword.

NOTE constant index is scoped to the loop body, assuming you want to see the value of index after the loop ends, or if you want index to be a variable instead of a constant, you must declare index yourself before the loop.

Assuming you don't need all the values in the range, you can ignore the value of the element by using an underscore in the position of the variable.

Let base = 3let Power = 10var Answer = 1for _ in 1...power {    answer *= base}println ("\ (base) to the power of \ (Power) is \ (answer) ")//Prints" 3 to the power of 59049 "
This sample calculates the power of the base (in the example, 3 of the 10-second party).

The sample starts at 1 by 3, takes 10 times, uses a half-closed interval from 0 to 9 (there is a problem here, the original is using a half-closed loop, start with 0 and ends With9, but the sample does not have a half-closed interval nor 0 to 9 AH).

This calculation does not need to know the value of each cycle counter, only need to give answer after each loop to multiply base.

The underscore used for the position of the loop variable causes each loop to ignore the value of the loop variable and does not provide a way to get the value of the loop variable.

Iterate through the elements in the array using the for-in loop:

Let names = ["Anna", "Alex", "Brian", "Jack"]for name in Names {    println ("Hello, \ (name)!")} Hello, anna!//hello, alex!//hello, brian!//hello, jack!
You can also traverse the key-value to get the dictionary.

Each meta-tuple (key, value) of a dictionary is returned. You can parse its members into a specified constant in order to be used in a loop. The following example resolves the key of the dictionary to the constant animalname. The value of the dictionary is resolved to the 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 order in which the elements in the dictionary are traversed is not related to the order in which they were inserted. The elements in the dictionary are unordered, and there is no guarantee of the order in which they are traversed.

In addition to arrays and dictionaries, you can also use the for-in loop to iterate through the characters in a string:

For character in "Hello" {    println (character)}//h//e//l//l//o


For-condition-increment

In addition to the for-in loop, Swift supports traditional C-style for loops with conditional and incrementing statements:

for var index = 0; Index < 3; ++index {    println ("index")}//index is 0//index was 1//index is 2
The general format of this cycle is this:

for initialization; condition; Increment {
Statements
}

As with C, the semicolon separates the three parts of the loop definition. However, unlike C, Swift does not need to be initialization; condition; Increment outer brackets.

The running order of the loops is as follows:

    1. When the first loop is entered, the initialization expression (initialization) is run, creating constants or variables that the loop might use.

    2. The conditional expression is run.

      Suppose the conditional expression evaluates to False. The loop ends and the program runs the loop body after the code. Assume that the conditional expression is true. The loop body is run.

    3. The increment statement is not run until all statements in the loop body have run out. This statement is generally used to increment or decrement the counter. or update values for variables that have already been initialized based on the statement output.

      When the increment statement finishes running. The program returns to the second step, and the conditional statement is run again.

The loop format and the running process can be expressed in the following equivalent form:

Initialization
While condition {
Statements
Increment
}

Constants and variables declared in an initialization expression (such as var index = 0) can only be used in this for loop. To use index at the end of a loop, you must declare index before the loop.

var index:intfor index = 0; Index < 3; ++index {    println ("index")}//index is 0//index was 1//index is 2println ("The loop statements were execut Ed \ (index) times ")//prints" The loop statements were executed 3 times "
Note that the value of index is 3 instead of 2 after the loop has completely ended. The last increment statement ++index is run, index becomes 3, and index<3 equals false. The loop ends.



2.while Cycle

The while loop repeatedly runs the loop body until the condition becomes false. Such loops are well suited for situations where the number of loops is unknown before the loop body runs. Swift provides two form of while loop:

    • While: The value of the condition is evaluated before each run of the loop body.
    • Do-while: Calculates the value of the condition after each run of the loop body.

While
The while loop starts with a computed conditional expression. If the condition is true, the loop body is run repeatedly knowing that the condition is false, the following is the general form of the while loop

While condition {

Statements

}

Play a snake with a ladder tour below:



Game rules:

    • The chessboard has 25 squares, and the purpose of the game is to reach or exceed the 25th block.

    • Each time round, you need to shake the dice to determine how many times you walk, and the route as seen by the dotted line.
    • Let's say you get to the bottom of the ladder at the end of the round and go up the ladder.

    • Let's say you hit your tongue at the end of the round. Just follow the shot and move it down.

The chessboard can be represented by an array of int.

The checkerboard size is stored using a constant Finalsquare, which initializes the array and checks the game for customs clearance later.

The chessboard is initialized with 26 zero. Instead of 25 (subscript from 0 to 25):

Let Finalsquare = 25var board = int[] (count:finalsquare + 1, repeatedvalue:0)
Some squares involving snakes and ladders are set to a special value. The square next to the bottom of the ladder is set to an integer to move upward. The squares next to the snake's head are set to a negative number to slide:

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

The 3rd grid has a ladder. Able to climb to the 11th grid, so borad[03] is set to +8, above the integer preceded by a plus sign knowledge in order to look clearer, subscript less than 10 of the front plus 0 is just for the code neatly. (The plus and the extra 0 are not required.) But this adds to the clarity of the code.

The game starts from the No. 0 grid. is outside the lower left corner of the chessboard. The first dice can be moved to the board:

var square = 0var Diceroll = 0while 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 BOA Rd, move up or down for a snake or a ladder        square + = Board[square]    }}println ("Customs clearance!

")

The above example uses a very easy way to roll the dice. Let Diceroll start from 0, each cycle to him plus 1,++diceroll return is +1 after the value, so when diceroll+1 equals 7 when the Diceroll set to 1, so the result of the dice is 1,2,3,4,5,6,1,2,3 ... Instead of using random numbers.

After the dice are cast, the player moves diceroll the corresponding number of cells. Suppose the player moves after the number of lattice is greater than or equal to 25 to win. In this case, the code detects whether the current position is smaller than the checkerboard number after the move. Assume that the value in the grid is smaller than the number of checkers, assuming it is not small. That's a clear pass. The value stored in that lattice is the number of grids that climb up a ladder or crawl down a snake.

Assuming this inference is not added, Board[square] is likely to get a value outside the range of the array board, which will cause an execution error.

Suppose today Squre equals 26. The code will go to get board[26]. This subscript exceeds the range of the array board.

After the current loop body has run out, run the loop condition statement to see if the loop continues to run. Suppose the player has moved to or exceeds the 25th grid. The result of the loop condition is false and the game is over.

This example uses the while loop to be more appropriate. Because you do not know the number of times the game is going to start before the cycle starts. Instead, the loop is kept running until a particular condition is met before it stops.

Do-while

There is also a while loop Do-while first to run the loop body. Then we infer the loop condition. It then loops through the loop body until the loop condition is false.

The following are the general forms of Do-while:

do {
Statements
} while condition

The following is also a game of snakes and ladders. This time using Do-while instead of while. Finalsquare,board,square and Diceroll are also initialized in the same way as above:

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

The first step in this game cycle is to check if it's on a ladder or snake. Since no ladder can directly reach the 25th grid, it is impossible for the player to move directly through the ladder. So the first step in the loop is to check the snakes or ladders safely. (It seems awkward to read here is not explained clearly, it should be said that the first step in the loop with Do-while can directly add the corresponding number of the current lattice, instead of rolling the dice, because the dice move and then it is possible to reach 25, then you need to climb the ladder before the IF, but suppose to climb the ladder first , you don't have to infer and then roll the dice. It is impossible to pass through the ladder as it is seen from the picture. )

The game starts when the player in the No. 0 grid, Board[0] or 0, no impact:

Do {<span style= ' white-space:pre ' ></span>//move up or down for a snake or Ladder<span style= "white-space:p Re "></span>square + = Board[square]<span style=" white-space:pre "></span>//roll the Dice<span Style= "White-space:pre" ></span>if ++diceroll = = 7 {diceroll = 1}<span style= "White-space:pre" ></ span>//move by the rolled amount<span style= "White-space:pre" ></span>square + = Diceroll} while square < ; Finalsquareprintln ("Game over!")
The code checks the ladder or snake and then moves through the dice. And then a round of loops ends.

The loop condition is the same as the previous one, but this time, when the loop condition is only completed the first cycle will be the first calculation. For this game, the Do-while cycle is more appropriate than the while period. On the Do-while loop, when the loop condition is determined squre but on the blackboard, he starts the next cycle, and enters the loop to start running Squre+=board[square]. This omitted the front square check border.

7.Swift Translation Tutorial Series-The process of controlling loops

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.