Swift Control Statements

Source: Internet
Author: User
Tags case statement terminates



Control flow refers to "logical control statements", including if, If-else, for, for-in, while, do-while, switch, and so on. Most of them are similar to OC, but Swift has enhanced the functionality of control statements in certain conveniences. such as the introduction of For-in..<and the...operator, switch statements are very different. This article also focuses only on for-in and switch statements.


for-in


The for-in statement is substantially different from the for-in statement in OC, but there are two new symbols:..<(similar to Pythonrange()) and...:


    • ..<The interval described is a semi-closed interval (left closed right), which is0..<2represented[0,2)(0<=x<2, where x is an integer);
    • ...The interval described is a fully closed interval (left closed right), which is0...2represented[0,2](0<=x<=2, where x is an integer);


P.s:swift just started to launch,..<the prototype is.., fortunately soon in the subsequent version of the change..<, otherwise it is a disaster! Looking at a language a little bit of progress, finally developing into a great language is a very good thing, Swift will develop into a great language? I think it will!
P.S: I personally think that...is not a good design, why do you want such an operator? Hope to find the answer in the future!


Switch


Both the switch statement and the IF statement belong条件语句, and switch attempts to match a value to several patterns (pattern). The switch statement executes the corresponding code according to the first successful pattern. When it is possible to do more, you typically replace the IF statement with a switch statement, as follows:


switch someValueToConsider {
case value1:
// respond to value1
case value2, value3:
// respond to value2 or value3
default:
// otherwise, do something else
}


Switch statements consist of multiple case. To match some of the more specific values, Swift provides several more complex patterns of matching that will be mentioned later in this section.



SWIFT specifies that the switch statement must be "complete". This means that every possible value must have at least onecaseblock corresponding to it. In cases where it is not possible to cover all values, you can use the defaultdefaultblock to satisfy that requirement, which must be on the last side of the switch statement.


There is no implicit fallthrough


In C and OC, when writing a switch statement, be sure tocaseadd a sentence at the end of each statement to ensure that thebreak;switch code block terminates, or the next Case/default block is executed, which is referred to in Swift as " fallthrough".



Unlike the switch statements in C and OC, in Swift, when the code in the matchingcaseblock finishes executing, the program automatically terminates the switch statement without continuing to execute the nextcaseblock. This means that you do not need to explicitly use the break statement in acaseblock, which makes the switch statement more secure, easier to use, and avoids errors caused by forgetting to write abreakstatement.



In addition, Swift also stipulates that each case statement must contain at least one statement, such that writing code is invalid as follows, because the first block is empty:


let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// this will report a compile-time error


A case can also contain multiple matching patterns, with different pattern separated by commas,.


Range Matching


caseThe pattern of a block can be a range, as follows:


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"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way."
Meta-group


You can use tuples toswitchtest multiple values in the same statement. An element in a tuple can be a value, or it can be a range. In addition, using underscores_to match all possible values, the following example shows how to use a(Int, Int)tuple of types to classify points in a cluster(x, y):


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")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box"








In the above example, the switch statement determines whether a point is the origin (0, 0), whether on the red X-axis, on the yellow y-axis, in a 4x4 rectangle centered on the origin, or outside of the rectangle.



Unlike the C language, Swift allows multiple case to match the same value. In fact, in this case, the point (0, 0) can match all four cases. However, if there are multiple matches, only the first case block that is matched is executed . Consider that the points (0, 0) will match firstcase (0, 0), so that the remaining case blocks that match (0, 0) will be ignored.


Value Bindings


When multiple values match (using tuple), we often need to use the local value of the detected value, and the switch statement allows the value binding in the case as follows:


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 an y value of \(y)")
case (x, y):
println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2"


In this example, the switch statement determines whether a point is on the x-axis and the y-axis, or somewhere else.





WHERE statement


There is also a keyword in swiftwherethat is commonly used to handle more complex pattern matching, and where statements using the keyword bootstrap in a casewherecan be used to determine additional conditions:


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")
}


In this example, the switch statement determines whether a point is on the Green Line (y=x), on the Purple Line (y=-x), or not on the diagonal.





Control Transfer Statements


Control transfer code can change the order of your code execution, through which you can control the code jump, in Swift, there are four kinds of control transfer statements:


    • Continue
    • Break
    • Fallthrough
    • Return


In addition, Swift introduces "labeled statements", which is used to facilitate more flexible control transfer.



Continue, break, return these control statements are not different from the control statements we know in C and OC, so we will not repeat them here; so this section includes:


    • Switch and break;
    • Switch and Fallthrough;
    • labeled statements;
Switch and break


As mentioned above, in C and OC, it is often necessary tocaseadd code behind the block,break;because if this is not the case, then the switch statement executes subsequent case statements (note that the following pattern is not checked, Instead, the body code of the subsequent case is executed directly, but in Swift, this is not necessary because in Swift's switch statement, when the code in the matching case block finishes executing, the program automatically terminates the switch statement without continuing the next case block.



Therefore, it is not necessary to explicitly use the break instruction in the switch statement. This is not the case, however, because Swift also has a requirement that each case statement must contain at least one statement. However, in some case branches in some cases, you may not really want to do anything, other languages are used,;but the SWIFT statement does not need to use;, at this time the general use of the break statement instead, as follows:


let numberSymbol: Character = "Three" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "?", "One", "?":
possibleIntegerValue = 1
case "2", "?", "Two", "?":
possibleIntegerValue = 2
case "3", "?", "Three", "?":
possibleIntegerValue = 3
case "4", "?", "four", "?":
possibleIntegerValue = 4
default:
break
}
Fallthrough


This section briefly talks about Fallthrough, which is a new gadget.



As mentioned above, switch in the swift language does not fall into the next case branch from the previous case branch. Instead, as soon as the first matching case branch completes the statement it needs to execute, the entire switch code block completes its execution. In contrast, the C language requires that you display the Insert break statement to the end of each switch branch to prevent automatic fall into the next case branch. This avoidance of the default fall into the next branch of the swift language means that its switch function is clearer and more predictable than the C language, and avoids the errors that can be caused by unintentionally executing multiple case branches.



But sometimes it does require artificial fallthrough, when thefallthroughkeyword comes in handy, as follows:


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"
}
println(description)
// prints "The number 5 is a prime number, and also an integer."


It is worth mentioning that the Fallthrough keyword does not check the next match condition that will fall into the executed case. Fallthrough simply allows code execution to continue to connect to the execution code in the next case, which is the same as the switch statement attribute in the C language standard.


labeled Statements


In the swift language, you can create complex control flow structures by nesting the loop body and the switch code block in the loop body (for loop or while loop) and switch code block. However, both the loop body and the switch code block can use the break statement to end the entire block of code prematurely. Therefore, it is useful to indicate which loop body or switch block of code The break statement wants to terminate. Similarly, if you have many nested loop bodies, it can also be useful to indicate which loop body the continue statement wants to affect.



To do this, you can use tags to mark a loop body or switch block of code, and when you use break or continue, you can control that tag to represent the object's interruption or execution.



A tagged statement is generated by placing a label in front of the same line in the keyword of the statement, and with a colon followed by the label. The following is the syntax for a while loop body, and the same rules apply to all loop bodies and switch code blocks:


labelName: while condition {
// statements
}


The use of the label is very simple, following a code that demonstrates the application of the label:


gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
square += diceRoll
square += board[square]
}
}
println("Game over!")


Obviously, thelabeled statementsability to implement statements similar to those in C can be implementedgoto.



Swift Control Statements


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.