Swift 程式流程式控制制

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   for   re   c   

Swift採用類同c語言的流程式控制制語句,if, for, for-in,  while,  do-while , switch, break, continue .Swift語言的Switch語句自動添加了break效果,這樣你可以不用沒個case後面再寫break.同c語言不同,swift語言的if for while 等,沒有括弧來括運算式

1: if 語句。if語句只對邏輯值檢測。這裡不同於c語言的if語句是檢測是否 非0.

var bFlag:Bool = trueif bFlag {    println("\(bFlag)")}

2: for語句,for語句的用法類似於c語言for語句

 var index:Int = 0for index; index < 5; index++ {     println("\(index)\n")  }

3: for-in語句用於多集合的遍曆

for item in 1..5 {    println("\(item) ")}

如果不使用集合元素可以用 _忽略

var iCount : Int = 1let iBase : Int = 2for _ in 1...3 {  iCount *=  iBase}println("\(iCount)")

用for-in 遍曆數組

let array = [1,3,5,7]for item in array {    println("\(item) ")}

for-in 遍曆字典 

let dic  = ["key1":"value1", "key2":"value2", "key3":"value3"]for (key, value) in dic {    println("key:\(key) value:\(value) \n")}

4:while迴圈。while迴圈判斷邏輯值

var bFlag:Bool = truevar iCount:Int = 0while bFlag{    iCount++    if iCount > 3 {        bFlag = false    }    println("\(iCount)\n")}

5: do-while 。while/ do-while 迴圈控制流程程是和c語言一樣的,只是他們的判斷是邏輯值而不是c語言那樣的 !0 值。

var bFlag:Bool = truevar iCount:Int = 0do{    iCount++    if iCount > 3 {        bFlag = false    }    println("\(iCount)\n")}while bFlag

6:switch 語句。switch語句必須是完備的語句,defualt語句必須在所有case語句的最後。每個case後switch語句會自動break。case 塊中不允許空語句。一個case條件可以使用範圍匹配。同時case條件可以使用元組匹配,而且元組可以用 "_" 表示任何值

let iCount :Int = 3switch iCount{case 1...6:    println("in")case 7..9:    println("out")default:    println("def")}

 

let character: Character = "c"switch character{case "a", "b", "c" :    println("xx")    case "d", "e":    println("oo")default:    println("def")}

 

var somePointe = (1,2)switch somePointe {case(0, 0):    println("0.0")case(_, 2):    println("_, 2")//_匹配 進這句case(1, 2):    println("1, 2")//不會進,前面已經breaddefault:    println("def")    }

 

fallthrough  關鍵字是在switch語句中去除break,讓代碼可以繼續下個語句。 
相關文章

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.