7. Swift tutorial translation series-loop of Control Flow

Source: Internet
Author: User

English region http: // download.csdn.net/detail/tsingheng/7480427

Swift provides a control flow structure similar to the C language. The for loop and while loop are used to execute tasks multiple times. if and switch statements execute different branch codes according to different conditions. The break and continue statements redirect the execution process to other statements.

In addition to the traditional for-condition-increment loop in C, Swift also adds the for-in loop to make it easy to traverse arrays, dictionaries, ranges, strings or other sequences.

The switch statement of Swift is more powerful than the switch statement of C language. A case statement in Swift does not run the subsequent case after execution, avoiding errors caused by forgetting to Write break in C. Case can match multiple types, including range matching, tuples, or a specific type (casts to a specific type ). The matched values in case can be bound to temporary constants or variables so that they can be used in case. Complex matching conditions can be represented by where.

1. for Loop

The for loop is executed repeatedly for a specified number of times. Swift provides two forms of for loop:

  • For-in executes each element once in a range, sequence, set, or series.
  • For-condition-increment is executed repeatedly until a special condition is met. Generally, the counter increments after each loop.

For-in

You can use a for-in loop to traverse the elements of a set, such as numbers in a range, elements in an array, or characters in a string.

The following example shows the line 5 in the multiplication table:

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 element set to be traversed is a closed interval between 1 and 5 created using. The index value is set to the first value 1 in the range, and the statement in the loop body is executed. In this example, the loop body contains only one statement, that is, the output multiplication table. After the statement is executed, the index value is updated with the second value 2 in the range, and the output statement is executed again. This process is always the last value in the range.

In the above qualifications, index is a constant and is automatically assigned a value each time a loop is executed. In this case, the index does not need to be declared before use. Directly Using index in for-in is equivalent to implicitly declaring the constant index. You do not need to use the let keyword.

NOTE constant index only applies to the loop body. If you want to view the index value after the loop ends, or you want to use index as a variable rather than a constant, then you must declare the index yourself before the loop.

If you do not need all values in the range, you can ignore the value of an element by using underscores 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 10 is 59049"
In this example, calculate the power of the base (in this example, the power is 10 of 3 ). The example starts from 1 to 3, multiplied by 10 times, and uses a semi-closed range from 0 to 9 (is there a problem here, the original Article is using a half-closed loop that start with 0 and ends with9, but the example does not have a semi-closed interval or 0 to 9 ). This calculation does not need to know the value of the counter of each loop. It only needs to assign answer to the base after each loop. The underline used for the position of the loop variable causes the value of the loop variable to be ignored during each loop process, and does not provide a way to get the value of the loop variable.

Use the for-in loop to traverse the elements in the array:

let names = ["Anna", "Alex", "Brian", "Jack"]for name in names {    println("Hello, \(name)!")}// Hello, Anna!// Hello, Alex!// Hello, Brian!// Hello, Jack!
You can also retrieve the dictionary's key-value pair through traversal. Each element of the dictionary is returned as a key (value). You can resolve its members to a specified constant for use in a loop. The following example resolves the dictionary key to the constant animalName, And the dictionary value to the constant legCount:

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 traversal sequence of the elements in the dictionary is irrelevant to the insertion sequence. The elements in the dictionary are unordered, and the order of traversal is not guaranteed.

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

for character in "Hello" {    println(character)}// H// e// l// l// o


For-condition-increment

In addition to the for-in loop, swift also supports the traditional C-style for loop with conditions and incremental statements:

for var index = 0; index < 3; ++index {    println("index is \(index)")}// index is 0// index is 1// index is 2
The general format of this loop is as follows:

For initialization; condition; increment {
Statements
}

Like C, semicolons separate the three parts of the loop definition, but unlike C, Swift does not need to add parentheses outside initialization; condition; increment.

The execution sequence of the loop is as follows:

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

Initialization
While condition {
Statements
Increment
}

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

var index: Intfor index = 0; index < 3; ++index {    println("index is \(index)")}// index is 0// index is 1// index is 2println("The loop statements were executed \(index) times")// prints "The loop statements were executed 3 times"
Note that after the loop ends completely, the index value is 3 instead of 2. The last incremental statement + + index is executed, the index changes to 3, and the index <3 is equal to false, and the loop ends.

2. while Loop

The while LOOP executes the body repeatedly until the condition changes to false. This loop is very suitable for situations where the number of loops is unknown before the loop body is executed. Swift provides two while LOOP forms:

  • While: Calculate the condition value before each execution of the loop body.
  • Do-while: calculates the value of the condition after each execution of the loop body.

While
The while loop starts with a calculated conditional expression. If the condition is true, the loop body is repeatedly executed and the condition is false. below is the general form of the while loop.

While condition {

Statements

}

Let's have a tour of snakes and ladders:



Game rules:

  • The Board has 25 squares. The game aims to reach or exceed 25th grids.
  • In each round, you need to shake the cursor to decide how many lines you should take, as shown in the dotted line.
  • If you arrive at the bottom of the ladder at the end of this round, you will follow the ladder.
  • If you encounter your tongue at the end of this round, you can move it down to the bottom.

The chessboard can be represented by an Int array. The size of the board is stored using the constant finalSquare to initialize the array and check whether the game passes customs. The checker uses 26 zeros for initialization, instead of 25 (the subscript ranges from 0 to 25 ):

let finalSquare = 25var board = Int[](count: finalSquare + 1, repeatedValue: 0)
Some squares involving snakes and ladders should be set to special values. The square at the bottom of the ladder is set to an integer to move up, while the square at the bottom of the snake is set to a negative number to 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

There is a ladder in the 1949th lattice, so borad [03] is set to + 8, and the plus sign is added before the integer to make it clearer, add 0 to the front of a subscript smaller than 10 to make the code neat. (Both the plus sign and the excess 0 are not necessary, but the addition of this sign can make the code clearer .)

The game starts from 0th cells, that is, outside the lower left corner of the Board. The first time you throw the keyboard, you can move it to the Board:

Var square = 0var 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 re still on the board, move up or down for a snake or a ladder square + = board [square]} println ("customs clearance! ")
In the above example, a simple method is used to throw a token. Let diceRoll start from 0 and Add 1 to each loop. ++ diceRoll returns the value after + 1. Therefore, when diceRoll + 1 equals 7, set diceRoll to 1, so the result of explain is 1, 2, 3, 4, 5, 6, 1, 2, 3... instead of using random numbers.

After the player is thrown out, the player moves the number of cells corresponding to diceRoll. If the number of cells after the player moves is greater than or equal to 25, the player wins. Considering this situation, the code checks whether the current position is smaller than the number of Board space after moving. If it is smaller than the number of Board space, it adds the value in that grid. If it is not small, it indicates that it passes the examination. The value stored in the grid is the number of cells that climb up the ladder or down the snake. If this judgment is not added, the board [square] may need to obtain a value out of the range of the array board, which will cause a running error. If squre is equal to 26, the code will get board [26]. This subscript exceeds the range of the array board.

After the current loop body is executed, run the loop Condition Statement to check whether the loop continues. If the player has been moved to or more than 25th cells, the loop condition is false, and the game is over.

In this example, the while loop is suitable, because the number of times the game is to be played is unknown before the loop starts. Instead, a loop is executed until a specific condition is met.

Do-while

In another while LOOP, do-while executes the loop body once before judging the loop condition. Then, the loop body is cyclically executed until the loop condition is false.

Below is the general form of do-while:

Do {
Statements
} While condition

The following is a game of snakes and ladders. do-while instead of while is used this time. FinalSquare, board, square, and diceRoll are 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 loop is to check whether it is on a ladder or snake. Because no ladder can pass to the 25th level, it is impossible for players to move through the ladder and pass through the Customs. So the first step of the loop is to directly check whether the snake or ladder is safe. (It seems that I have not explained it clearly. It should be that when do-while is used, the number corresponding to the current grid can be directly added in the first step of the loop, rather than throwing the cursor first, because throttling and moving may reach 25 cells, you need the front if before you climb the ladder, but if you climb the ladder first, you don't have to judge and then throw the cursor, as shown in the figure, it is impossible to pass through the ladder .)

At the beginning of the game, there was no impact on the player's 0th lattice, board [0] or 0:

do {<span style="white-space:pre"></span>// move up or down for a snake or ladder<span style="white-space:pre"></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!")
After the code checks a ladder or a snake, it moves by throwing a finger and ends a loop.

The loop condition is the same as above, but this loop condition is calculated for the first time only when the first loop ends. For this game, the do-while loop is more suitable than the while loop. In the do-while loop above, when the loop condition determines that squre is still on the board, start the next loop and execute squre + = board [square] at the beginning of the loop. This removes the need for square boundary checks.

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.