Swift Chapter II: The use of control statements and methods

Source: Internet
Author: User


This issue mainly talk about the use of common control statements and methods


The first is the loop statement

Common for in (this is simple in the previous period, similar to other languages)

var arraybu = ["Mage", "Paladin", "Warlock", "Druid", "rogue"]for item in ARRAYBU {println (item)}var DICTIONARYBU = ["Occupation": "Mage", "mode": "Arena"]for (key, value) in Dictionarybu {println ("\ (key): \ (value)")}for var i = 0; I <= 5; i++ {println (i)}for i in 0...5 {println (i)}for char in "Sun Wanhua" {println (char)}


Then there is the while and does while (similar to other languages, do not make too much explanation)

var x = 0var result = 0while x < {result + = x x++}println (result) var y = 0do {y--} while y > -5println (y)


Next is the conditional statement

Common if else (similar to other languages, do not explain too much)

var temp = 30if Temp < {println (0)} else if temp > all && temp < println (1)} else {Prin TLN (2)}


 var flag =  "SSE"//At the same time meet a few conditions, only go the first condition//Here no more break, the default after each execution of break//this is not a single can only put the integer type and enumeration type Oh, We can also put strings and ganso and other types to do the basis Oh switch  (flag)  {    case  "Happy":         println ("Happy")         case  "sad",  " Lose ":         println (" sadness ")          case let test where test.hassuffix ("se"):         println ("What do you think I'm doing")         default:         println ("no Feeling")}var number = -5switch  (number)  {     case 0...9:        println ("This is single digit")      Case 10...99:        println ("This is a 10-digit number")     case  100...9999:         println ("This is a big number")     default:         println ("This is negative")}let point =  (6, 6) switch  (point)  {    case  (0, 0):         println (" Origin ")     case  (_, 0):         println (" X-axis " )     case  (0, let y):         println ("points on Y axis \ (y)")     case  ( -2...2, -2...2):         println ("Rectangle  -2...2  area")     case let  (X, y)  where x == y | |  x == -y:        println ("On the diagonal")      case  (let x, let y):         println ("Random point \ (x), \ (y)")     default:        println (" A point ")}


Next is the transfer statement

Common Continue,break,return,fallthrough (often used with switch nesting)

The top three, like other languages, do not have much explanation.

 et str =  "Great minds think alick" for char in str {     switch char {        case  "A",   "E",  "I",  "O",  "U",  " ":             continue        default: println (char)      }}for i in 1...10 {    println (i)      if i > 5 {        break     }}let tempNumber = 5var descript =  "digital \ (tempnumber) yes"// Here we use the Fallthrough to play the role of the bridge, to associate the two statements together and execute the switch tempnumber {    case 2, 3,  5, 7, 11, 13:        descript +=  "a prime number, It is also a "    fallthrough    default:        descript +=  "Integer"} println (descript)


Then let's introduce the basic introduction and use of the method.

Here we use Func to define the method

Typically: Func method name (parameter, parameter), return parameter type {}

Called by: Method name (parameter, parameter)

 //single parameter  func sayhello (username: string)  ->string {    let  greeting =  "Hello, \ (username)"     return greeting}println (SayHello ("SwH" )//multi-parameter Func sumof (numbera:int, numberb:int)  ->Int {    return  Numbera + numberb}println (Sumof (10, 5))//No return value Func saygoodbye (username: string)  {     println ("Welcome \ (username) next time")}saygoodbye ("Kutian")//No return value no parameter func saywelcome ()   {    println ("Welcome to Swift")}saywelcome ()//single parameter, return value is multi-parameter, similar to meta-ancestor func countstring (value:string )  ->  (Vowels:int, consonants:int, others:int)  {    var  Vowels = 0, consonants = 0, others = 0    for  char in value {        switch string (char). Lowercasestring&nbsP {            case  "A",  "E",  "I",   "O",  "U":                 vowels++            case  "B",  "C":                 others++             default:                 consonants++         }    }    return  (vowels, consonants,  others)}let count = countstring ("some string in english!") println (count.vowels)//multi-parameter, and the last parameter gives the default value func joinstring (firstvalue value1:string, secondvalue  value2:string, betweener joiner:string =  " - ")  ->string {    return value1  + joiner + value2}println (Joinstring (firstvalue:  "A", secondvalue:  "B"))// "#" for the above method of shorthand, mainly to give the interpretation of parameters, similar to O-c, easy to read func joinstringnew (#firstValue:string,  #secondValue:string,  betweener:string =  " - ")  ->String {    return  Firstvalue + betweener + secondvalue}println (Joinstringnew (firstValue:  "W",  secondvalue:  "a", betweener:  "+")//variable parameters, can be transmitted any func sumofnumbers (numbers:double  ...)  ->double {    var total:double = 0    for  num in numbers {        total += num     }    return total}println (Sumofnumbers (1, 5, 8))// inout  indicates that the argument is the address, so we need to pass the argument againAdd "&"//Here is similar to C language function Func modifyint (inout a:int, inout b:int)  {     a += 3    b = 6}var someInt = 3var  Anotherint = 9modifyint (&someint, &anotherint) println ("\ (Someint),  \ (anotherInt)") Func addtwoint (A:int, b:int)  ->int {    return a + b The}//method also counts as a class in swift, so you can also define the type of the variable Var mathfunc: (int, int)  ->int = addtwointprintln ( Mathfunc (1,&NBSP;2))//methods can also act as parameters or return values in other methods Func printmathresult (mathfunction: (int, int)  ->int ,  a:int, b:int)  {    println (Mathfunction (a, b))}println ( Printmathresult (addtwoint, 3, 5)) func firstfunction (I:int)  ->Int {     return i + 1}func secondfunction (I:int)  ->Int {     return i + 2}func&nbsP;choosefunction (Which:bool)  ->  (Int)  ->Int {    return  which ? firstfunction : secondfunction}//here targetfunction is equivalent to first and second a method () let  Targetfunction = choosefunction (False) println (Targetfunction (1))//nested use//in methods, we can also define methods, and invoke the func of these definitions  newchoosefunction (Which:bool)  ->  (Int)  -> Int {         func firstfunctionnew (I:int)  ->Int {         return i + 1    }         func secondfunctionnew (I:int)  ->Int {         return i + 2    }         return which ? firstfunction : secondfunction}let targetfunctionnew =  Newchoosefunction (False) PRINtln (Targetfunctionnew (1)) 


All right, so much for this.


This article is from the "Neusoft iOS Alumni Group Technology Blog" blog, please be sure to keep this source http://neusoftios.blog.51cto.com/9977509/1669808

Swift Chapter II: The use of control statements and methods

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.