Swift Learning-06-Control flow

Source: Internet
Author: User

Control flow

Swift provides a variety of control flow structures, including a while loop that can be executed multiple times, select if, Guard, and switch statements that perform different branches based on specific criteria, and break and continue statements that control the flow of jumps to other code locations

Swift also provides a for-in loop to make it easier to iterate over the group (array), the Dictionary (dictionary), the Range (range), the strings (string), and other sequence types

Swift's switch statement is more powerful than the C language, and in C, if a case accidentally misses a break, it runs through to the next scenario, Swift does not need to write cases, and does not have to write a break, so there is no penetration. Case can also match many different patterns, including interval matching, tuple (tuple), and transition to a specific type. The matching values in the case of swift statements can also be bound to temporary variables or constants, used in case, or where to describe more complex match conditions

For-in Cycle

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

For index in 1...5 {

Print ("\ (index) times 5 is \ (index*5)")

}

In the example above, index is a constant that is automatically copied each time the loop is started. In this case, the index does not need to be declared before it is used, and the word needs to be included in the circular declaration, and it can be implicitly declared without using the LET keyword declaration

If you do not need the value of each item in the interval sequence, you can use the (_) instead of the variable name to ignore the value

(_) (the variable that replaces the loop) can ignore the current value and does not provide access to the value when the loop is traversed

Let names = ["Anna", "Alex", "Brian", "Jack"]

For name in Names {

Print ("Hello, \ (names)")

}

You can also access its key-value pairs by traversing a dictionary, while traversing the dictionary. Each element of the dictionary is returned as a tuple of (key, value), and you can interpret (key, value) tuples with an explicit constant name in the for-in loop

Let Numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]

For (Animalname, Legcount) in Numberoflegs {

Print ("\ (animalname) s has \ (legcount) 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

While

The while loop starts by evaluating a condition and, if the condition is true, runs a statement repeatedly until the condition becomes false to end the skip

Repeat-while

Another form of a while loop, which differs from while by executing a loop of code blocks before judging the loop condition, and then repeating the loop to know the condition false

The Repeat-while loop of Swift language is similar to the do-while cycle of other languages

repeat{

//

}while condtion

Conditional statements

It is often useful to execute specific code based on specific criteria, and when an error occurs, you may want to run additional code, or, when the value is too large or too small, to display a message to the user, to implement these functions, you need to use the conditional statement

Swift provides two types of conditional statements, if statements, and switch statements, usually when the conditions are simple and possible, with an if statement, and the switch statement is more suitable for complex conditions, with more permutations, and in the switch It is more useful to use a pattern matching scenario

If

The simplest form of an if statement is to include only one condition, and the relevant code is executed when the condition is changed to True

var Temperatureinfahrenheit = 30

If Temperatureinfahrenheit <= 32 {

Print ("It ' s very cold, consider wearing a scarf")

}

Of course, the IF statement allows two to be executed, called the ELSE clause, that is, when the condition is FALSE, the Else statement is executed

Switch

The switch statement attempts to match a value to a number of patterns, and the switch statement executes the corresponding code according to the first successful pattern, often replacing the IF statement with a switch statement when there are possible cases

The simplest form of a switch statement is to compare a value to one or several of the same types

Switch 1 {

Case 1:

Print (1)

Default

Print ("No value")

}

The switch statement consists of multiple cases, each with the case keyword, and in order to match certain values, Swift provides several methods for more complex pattern matching.

Like the If statement, each case sick a a branch of code execution, and the switch statement determines which branch should be executed, and the process is called a more specified value switch

The switch statement must be complete, that is, each possible value must have at least one case branch advance corresponding, and in some cases where it is not possible to cover all values, you can use the default branch to cover all other cases where there are no corresponding values, the default branch must be The last side of the switch statement

For example

Let somecharacter:character = "Z"

Switch Somecharacter {

Case "a":

Print ("The first letter of the Alphbet")

Case "Z":

Print ("The last letter of the alphabet")

Default

Print ("Some other character")

}

There is no implicit cross-cutting

Unlike the switch statements in C and OC, in Swift, when the code that matches the case branch finishes executing, the program terminates the switch statement without continuing the next case branch, which means that the BRE is not required to be explicitly used in the case branch AK statement, which makes the switch statement more secure, easier to use, and avoids errors caused by break misses

Note: Although break is not required in swift, you can still use break to jump out before the code in the case branch is finished

Each branch case must contain at least one statement that cannot be empty under the branch

Let Anothercharacter:character = "a"

Switch Anothercharacter {

Case "a"://invalid, no statement under this branch

Case "A":

Print ("The Letter A")

Default

Print ("Not the letter A")

//}

This code will report a compilation error

Unlike the switch statement in C, in Swift, the switch statement does not match "a" and "a", whereas the above code causes an editor error, case "a": does not contain any executable statements, which avoids accidentally penetrating from a case branch to Another that makes the code more secure and more intuitive

In order for a single case to match both A and a, the two values can be composited into a composite match and separated by commas:

Let Anothercharacter:character = "a"

Switch Anothercharacter {

Case "A", "a":

Print ("The Letter A")

Default

Print ("Not the letter A")

}

Output "the letter A

Note: If you want to explicitly go through the case branch, use the Fallthrough statement

Interval matching

The pattern of a case branch can also be a range of values,

Let Approximatecount = 62

Let countedthings = "moons Orbiting Saturn"

var naturalcount:string

Switch Approximatecount {

Case 0:

Naturalcount = "No"

Case 1..<5:

Naturalcount = "a few"

Case 5..<12:

Naturalcount = "several"

Case 12..<100:

Naturalcount = "Dozens of"

Case 100..<1000:

Naturalcount = "hundreds of"

Default

Naturalcount = "many"

}

Print ("There is \ (Naturalcount) \ (countedthings)")

Output "There is dozens of moons orbiting Saturn."

Meta-group

We can use tuples to test multiple values in the same switch statement, elements in tuples can be values or intervals, and, in addition, use underscores (_) to match all possible values

Let Somepoint = (1, 1)

Switch Somepoint {

Case (0, 0):

Print ("(0, 0) is at the origin")

Case (_, 0):

Print ("(\ (somepoint.0), 0) is on the x-axis")

Case (0, _):

Print ("(0, \ (somepoint.1)) is on the y-axis")

Case ( -2...2, -2...2):

Print ("(\ (somepoint.0), \ (Somepoint.1)) is inside the box")

Default

Print ("(\ (somepoint.0), \ (Somepoint.1)) is outside of the box")

}

Output "(1, 1) is inside the box"

Value binding (Bindings)

The case branch allows you to bind a matching value to a temporary constant or variable and use it in a branch of the shell-this behavior is called value binding because the matched value is in the case branch, bound to a temporary constant or variable

Let Anotherpoint = (2, 0)

Switch Anotherpoint {

Case (Let x, 0):

Print ("On the x-axis with an X value of \ (x)")

Case (0, let y):

Print ("On the y-axis with a Y value of \ (y)")

Case let (x, y):

Print ("somewhere else at (\ (x), \ (y))")

}

Where

The case branching pattern can use the where statement to determine additional conditions

Let Yetanotherpoint = (1,-1)

Switch Yetanotherpoint {

Case let (x, y) where x = = y:

Print ("(\ (x), \ (y)) is on the line x = = y")

Case let (x, y) where x = =-Y:

Print ("(\ (x), \ (y)) is on the line x = = y")

Case let (x, y):

Print ("(\ (x), \ (y)) is just some arbitrary")

}

Output "(1,-1) is on the line x = =-Y"

Compound match

When multiple conditions can be processed using the same method, these may be placed after the same case, and separated by commas, when any one of the patterns following the case matches, this branch will be matched, and if the match list is too long, you can also write

Let Somescharacter:character = "E"

Switch Somecharacter {

Case "A", "E", "I", "O", "U":

Print ("\ (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":

Print ("\ (somecharacter) is a consonant")

Default

Print ("\ (Somecharacter) is not a vowel or a consonant")

}

Output "E is a vowel"

Composite matching can also contain binding values, compound match all the matching pattern, must contain the same value binding, and no binding must obtain the same type of value, which ensures that regardless of the pattern in the compound match, the code within the branch can get the value of the binding, and the bound values have the same type

Control transfer Statements

The control transfer statement changes the order in which your code is executed, which allows you to jump through the code, and Swift has five types of control transfer statements:

Continne

Break

Fallthrough

Return

Throw

Continue

Continue tells a loop to stop the cycle immediately and start the next cycle again, just like saying ' This loop is done ', but it's not going to leave the whole loop body.

Let Puzzleinput = "great minds think alike"

var puzzleoutput = ""

For character in Puzzleinput.characters {

Switch character {

Case "A", "E", "I", "O", "U", "":

Continue

Default

Puzzleoutput.append (character)

}

}

Print (Puzzleoutput)

Break

The break statement immediately ends the execution of the entire control flow, and when you want to end a switch block or a loop body earlier, you can use the break

Break in a looping statement

When a break is used in a loop body, the execution of the loop body is immediately interrupted, and then the first line of code after the curly brace (}) representing the end of the loop body is skipped, and no more code for the loop is executed, and no further loops occur

Break in Switch

When a break is used in a switch, the execution of the switch code block is immediately interrupted, and the first line of code after the curly brace (}) representing the end of the switch code block is skipped.

This feature can be used to match or omit one or more branches, because Swift's switch needs to include all branches and does not allow empty branches to exist, something more obvious for your intentions, a need to deliberately match or ignore a branch, so when you want to ignore a branch, You can write a break statement within a branch, and when that branch is matched, the break statement within the branch immediately ends the switch code block

Note: When a switch branch tightly contains a comment, it is edited with an error, the comment is not a code statement and does not allow the switch branch to achieve the ignored effect, and you should use break to ignore a branch

Throughout

The switch in Swift does not fall from the previous case branch into the next case branch, as long as the first matching case branch completes the statement it needs to execute, and the entire switch block completes its execution, in contrast, C requires you to explicitly insert The break statement to the end of each case prevents the automatic fall into the next branch of the scenario, and Swift's avoidance falls into the next branching feature. A whole of his switch function is more clear and predictable than the C language, avoiding the unconscious execution of multiple cases branching to trigger The error

If you do need a C-language cross-cutting feature, you can use the Fallthrough keyword in each case branch that needs to be changed.

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."

}

Print (description)

Note: The Fallthrough keyword does not check the next match condition that will fall into the execution of the case branch, and fallthrough the code to continue to connect to the code in the next case, which is the same as the C standard switch statement feature.

Tagged statements

In Swift. You can nest loop bodies and add statements in loop bodies and conditional statements to create complex control flow structures, and both loop bodies and conditional statements can use the break statement to prematurely end the entire block of code

To do this, you can use the label (statement label) to mark a loop body or conditional statement, and for a conditional statement, you can use break tagging to end the marked statement, and for a loop statement, you can use break or C Ontinue tag to end or continue the execution of this tagged statement

Declaring a tagged statement is by placing a label in front of the same line of the keyword of the statement as the leading keyword for the statement, and following the label with a colon followed by the tag syntax of a while loop body, the same rule applies to all loop bodies and conditional statements

Early exit

Like an if statement. The execution of a guard depends on the Boolean value of an expression, and we can use the guard statement to require that the condition must be true to execute the code after the guard statement, unlike the IF statement, where a guard statement always has an ELSE clause. If the condition is not true then the else slave is executed. The code in the sentence

If the condition of the guard statement is met, the code following the guard statement brace is executed, and the condition of the optional binding Guard statement for the variable or constant can protect the code behind the guard statement

If the condition is not met, the code on the Else branch is executed, and the branch must transfer control to exit the code snippet that appears in the guard statement, which can be used to control the transfer of statements such as: Return, break, continue, or throw, or call a method or function

Using the Guard statement on demand will improve the readability of our code when compared to an if statement that can implement the same functionality, allowing your code to be executed coherently without having to wrap it in the else block, which will allow you to deal with the violation in a situation where the condition is immediately judged.

Detecting the availability of APIs

Swift's built-in support checks API availability, which ensures that we are no longer on the currently deployed machine, accidentally using an unusable API

The editor uses the information available in the SDK to verify that all APIs used in our code are available on the deployment target specified by the project, and if we try to use an unusable API, Swift will make an error in the edit

We use the availability condition (availability condition) in an If or guard statement to conditionally execute a piece of code to determine if the calling API is available at run time, and the editor uses the information obtained from the availability condition statement to verify that it is available in this block of code

If #available (IOS, MacOS 10.12, *) {

}else{

}

The above availability conditions specify that, in iOS, the code block of the IF statement is only run under iOS 10 and higher; In MacOS, only the MacOS 10.12 and later versions will run, and the last parameter (*) is required to specify that in all other platforms, if the version is higher than the minimum version specified by your device, the code block of the IF statement will also execute

In its general form, the availability condition uses a list of platform names and versions, the platform name can be iOS, MacOS, WatchOS and TvOS, in addition to specifying major version numbers like iOS 8, we can specify iOS 8.3 and MacOS 10.10 .3 Sub-version number

Swift Learning-06-Control flow

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.