Swift Control statements

Source: Internet
Author: User
Tags case statement

Objective

Swift provides a C-like process control structure that includes a for and while loops that can perform tasks multiple times. There are also the IF, guard, and switch statements that choose to execute different code branches based on specific criteria, as well as the break and continue statements that control the flow to other code.

Swift adds a for-in loop to make it easier to iterate over groups, dictionaries, ranges, strings, and other sequence types.

Swift's switch statement is more powerful than the C language. In the C language, if a case accidentally misses a break, it runs through the next scenario, and Swift does not have to write a break, so this cross-cutting situation does not occur. The case can also match more type patterns, including interval matching (range matching), tuple (tuple), and description of a specific type. The matching value in the case statement of switch can be determined by a temporary constant or variable inside the case body, or a more complex match condition can be described by the WHERE clause.

For loop (for Loops Statement)
    • For: As for loop with C language
    • For-in: Fast traversal of collections, sequences, etc.

For-in traversal range (where ...). Indicates the closed interval [1,5]):

For index in 1...5 {    print ("\ (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//what to ask hovertree.com//it can be converted for loop: for var index = 1; Index <= 5; ++index {   //...}

If we don't get the value, we can filter with an underscore (_), which is common:

Let base = 3let Power = 10var answer = 1//three points for the full closed interval [1, power]for _ in 1...power {    answer *= base}//what to ask Hovertree.com Two points plus a < is left closed right open [1, 5) var sum = 0for _ in 1..<5 {  sum + = 1}

A common way to iterate through arrays:

Let names = ["Anna", "Alex", "Brian", "Jack"]for the name in names {    print ("Hello, \ (name)!")} What to ask hovertree.com//or for (name, index) in Names.enumerate () {   //is also very common}

Common Traversal dictionaries:

Let Numberoflegs = ["Spider": 8, "Ant": 6, "Cat": 4]for (Animalname, Legcount) in Numberoflegs {    print ("\ (animalname) s Have \ (legcount) legs ")}//What to ask hovertree.com//we know that the key value pairs in the dictionary are represented by tuples, so you can access them directly through the tuple.

  

While loops (while loop Statement)
    • While loop, each time the loop starts, the calculation condition is met;
    • Repeat-while Loop, which calculates whether the condition meets at the end of the loop. The usage is exactly the same as the do-while in Objective-c.

Note: no do-while but repeat-while

var index = 10while Index > 0 {  index--}print (index)//0/* hwq2.com */index = 0repeat {//No do-while, only Repeat-whil E  print ("Test repeat")  index++} while index < 3

  

If condition statement (if Condition Statement)

The IF condition is false or true, or false.

The condition only prints if the index value is 3 and the result is true. If index = = 3 {  print ("3")}/* Hovertree.top */

  

Guide Statement (Guide Condition Statement)

guideThe syntax differs from IF, if the condition is true, then the else branch is not entered. guidesemantics are the means of guarding, that is to say, if you meet the conditions, nothing is done, otherwise you will go to the Else branch.

In the function, it is very common to exit the function when it is necessary to determine whether the required argument is empty. Guard Let name = dict["name"] else {    return}//asked hovertree.com

  

Switch statement (switch Statement)

The switch branch in Swift has many different places from the switch in objective-c:

    • There is no need to manually write break for each case in Swift
    • Case support interval matching in Swift
    • Case support tuples in Swift
    • Case support value binding in Swift
    • Case in Swift supports where conditional filtering
    • Case in Swift can place multiple values

No handwritten break, no implicit penetration:

var value = 1switch value {Case 1:  print (' only print 1 ') Case 2:  print (' Only print 2 ') Default:  print ("on Matche D value ")}//" only print 1\n "//Why Ask Hovertree.com

Support Match interval:

Let Approximatecount = 62let countedthings = "moons orbiting Saturn" var naturalcount:stringswitch 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." How to ask Hovertree.com

Supports tuples, which can be filtered for values that do not need to be fetched _ :

Let Httperror = (404, ' Http not Found ') switch httperror {case Let (code, _) Where code = = 404:  print (Httperror.1) case Let (code, msg) WHERE code = = 502:  print (msg) Default:  print ("default")}//ask Hovertree.com

Support for value binding:

Let Anotherpoint = (2, 0) switch Anotherpoint {case (Let x, 0):    print ("On the x-axis with a X value of \ (x)") Case (0, Let y):    print ("On the y-axis with a Y value of \ (y)") (x, y):    print ("somewhere else at (\ (x), \ (y))")}// Out "on the x-axis with an X value of 2"//Why Ask Hovertree.com

Support for where filter conditions:

Let point = (1, 3) The switch point {box let (x, y) where x > y:  print ("x > Y") Case let (x, _) where x > 2:  P  Rint ("x > 2") Case let (1, y) where y > 4:  print ("y > 4 and x = = 1") Case let (x, y) where x >= 1 && Y <=:  print ("OK")//Okdefault:  print ("error")}//what to ask Hovertree.com

Supports one case multiple values:

Let Numbersymbol:character = "three"  //Simplified Chinese numerals 3var possibleintegervalue:int?switch numbersymbol {case "1", "?", "one", "?":    Possibleintegervalue = 1case "2", "?", "Two", "?":    Possibleintegervalue = 2case "3", "?", "Three", "?":    Possibl Eintegervalue = 3case "4", "?", "Four", "?":    Possibleintegervalue = 4default:    break}//how to ask Hovertree.com

  

Controlling transfer statements (Control Transfer statements)

Swift has five kinds of control transfer statements:

    • Continue: Skip this cycle and go directly to the next loop
    • Break: Interrupts the nearest loop or interrupts a label (the next section explains)
    • Fallthrough: For switch branches through branches
    • Return: for function returns
    • Throw: Used to throw an exception

continueto skip an unsatisfied condition:

Let Puzzleinput = "great minds think alike" var puzzleoutput = "" for character in Puzzleinput.characters {    switch chara Cter {case    "a", "E", "I", "O", "U", "" ":        continue    default:        puzzleoutput.append (character)    }}print (puzzleoutput)//Output "grtmndsthnklk"//Why Ask Hovertree.com

To exit a loop with break:

For index in 1...5 {  If index >= 3 {    break  }}//is used in swift with break, it exits the swift statement directly index = 10for index in 20..< {    Switch index {case let        x where x < max:        print (x) case let    x where x > +:    break Default:        break}/* hwq2.com */

Use Fallthrough to run through Swift's case:

Let Integertodescribe = 5var Description = "the number \ (integertodescribe) are" switch Integertodescribe {case 2, 3, 5, 7, One, all,    +: Description + = "A prime number, and also"    Fallthroughdefault:    description + = "an Integer."} Print (description)//Output "The number 5 is a prime number, and also an integer." /* hwq2.com */

  

Label statement

For example, sometimes you need to jump to execute a piece of code when a certain condition is met, then it is useful to use the tag statement:

The syntax is as follows:

Label Name:while condition {    statements}/* hwq2.com */

An example of an official:

Gameloop:while Square! = finalsquare {    if ++diceroll = = 7 {diceroll = 1}    switch Square + diceroll {case    fi Nalsquare:        //Arrive at the last block, game over break Gameloop case let    newsquare where Newsquare > Finalsquare:        // Go beyond the last block and roll the dice again        continue gameloop    default:        //This mobile effective        square + = diceroll        square + + Board[square ]    }}print ("Game over!") /* Hovertree.top */

  

Check API availability

The syntax is as follows:

If #available (iOS 9, OSX 10.10, *) {    //iOS using iOS 9 API, OS X using OS X v10.10 API} else {    //using previous versions of iOS and OS X api}/* hovertree.top */

  

Read more about how to use this article: Swift Detection API availability

Written in the last

This blog post is the author in the process of learning Swift 2.1, may be some translation is not in place, please also point out. In addition, all examples are written by the author, if there is unreasonable, also hope to point out.

The best way to learn a language is not to read books, but to do hands-on, hands-on exercises. If you like, can pay attention to Oh, as far as possible 2-3 days to organize a swift 2.1 article. Here is the basic knowledge, if you are already a great God, please take a detour!

Recommendation: http://www.cnblogs.com/roucheng/p/swiftleixing.html

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.