"Swift" Learning Note (v)--control statement (If,switch,for-in,for,while,do-while)

Source: Internet
Author: User
Tags case statement

In the code business, conditional judgment is essential, and the statements that control the flow are similar in each language. Swift includes the following:


If condition statement (if-else) (If ... else)

Executes the relevant code when the condition is true. For example:

var a = 0

If a > 0 {

println ("a > 0")

}else if a = = 0{

println ("a = 0")


println ("a < 0")


The switch switch statement attempts to match a value to a number of patterns (pattern). The switch statement executes the corresponding code according to the first successful pattern.

For example:

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")
    println("\(someCharacter) is not a vowel or a consonant")

Switch has a few caveats:

1. The case statement must contain at least one line of code

2, the case statement can not contain break, it does not exist implicit in the run-through

3. Case can be matched in interval

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"
    naturalCount = "millions and millions of"
println("There are \(naturalCount) \(countedThings).")

4, tuples you can use tuples to test multiple values in the same switch statement. An element in a tuple can be a value, or it can be an interval. Also, use an underscore (_) to match all possible values

For example:

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")
    println("(\(somePoint.0), \(somePoint.1)) is outside of the box")

5. The pattern of value-bound case branching allows the matching values to be bound to a temporary constant or variable that can be referenced in the case branch-a behavior known as value binding

For example:

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
     println ("on the 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))")
// print "on the x-axis with an x value of 2"

6. Where Condition judgment

For example

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")
// Output "(1, -1) is on the line x == -y"

7. Be able to use Return,continue,break,fallthrough to change the control flow of all control statements. This is called control transfer.

A) The Continue statement tells a loop body to stop the loop iteration at once and start the next iteration of the loop again. It's like saying, "I'm done with this loop iteration," but I'm not going to leave the whole loop body.

b) The break statement immediately ends the execution of the entire control flow. When you want to end a switch code block or a loop body earlier, you can use the break statement, if for for-in while do-while these can be out of control with break,

c)Fallthrough throughout this and the 2nd.

D) The return statement immediately terminates execution of the current code and returns. Used in method control more.

8. Take a name for while

mainLabel: while a > 0{
	if a ==100 {
		break mainLabel

For loop for-in Loop

The For loop is used to execute a series of statements several times, as specified. Swift offers two kinds of for loop form:
A)for-in is used to traverse a range (range), sequence (sequence), set (collection), and all elements within the series (progression) to execute a series of statements.
b) forconditional increment (for-condition-increment) statements, which are used to repeatedly execute a series of statements until a specific condition is reached, typically by increasing the value of the counter after each loop is completed.

Traversal interval:

for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")

To iterate over an array:

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    println("Hello, \(name)!")

To traverse a dictionary collection:

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    println("\(animalName)s have \(legCount) legs")

You can also traverse characters:

for character in "Hello" {

Incremental loops:

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

While loop Do-while loop

While loop, each time the loop starts, the calculation condition is met;
Do-while Loop, which calculates whether the condition meets at the end of the loop.

While loop:

while condition {
while a > 0{
	println("a value \(a)");


Do-while Cycle

do {
} while condition
	println("a value \(a)")
}while a > 0

Wow, good strong, this cycle should be very cool ... Although the most used is for the loop, hehe.

"Swift" Learning Note (v)--control statement (If,switch,for-in,for,while,do-while)

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.