【swift-總結】控制流程

來源:互聯網
上載者:User

標籤:

for語句
//使用範圍for index in 1...5 {    print(index);}
//如果不需要使用迴圈變數,可以使用底線替代var time = 5;var i = 0for _ in 1...time {    print("第\(++i)次");}
//遍曆數組let numbers = ["one", "two", "three"];for number in numbers {    print(number);}
//遍曆字典let numStr = ["one": 1, "two": 2, "three": 3];for (str, num) in numStr {    print("\(str) is \(num)");}
//遍曆字串的字元for character in "hello".characters {    print(character);}
//經典for迴圈for var i=0; i<5; i++ {    print(i);}
//新型for迴圈for i in 0..<3 {    forstLoop += i;}相等於for var i=0; i<3; i++ {    forstLoop += i;}
switch語句

switch預設沒有穿透功能,不需要加break。如果要有穿透要使用fallthrough

let num = "one"switch num {case "one":    print("one");case "two":    print("two")default:    print("錯誤");}
switch num {case "one", "two":    print("你好");default:    print("不好");}
//使用範圍let score = 88;switch score {case 0...60:    print("不及格");case 60...70:    print("中等");case 70...80:    print("良好");case 80...100:    print("優秀");default:    print("超鬼");}
//使用點let point = (1, 1)switch point {case (0, 0):    print("原點");case (_, 0):    print("x軸上的點");case (0, _):    print("Y軸上的點");default:    print("普通點");}

賦值

let anotherPoint = (2, 0);switch anotherPoint {case (let x, 0):    print("在X軸上面的點是\(x)");case (0, let y):    print("在Y軸上面的點是\(y)");case let(x, y):    print("其他點(\(x), \(y))");}

還可以加where條件,有賦值的時候不能使用default

let wherePoint = (-1, -1);switch wherePoint {case let(x, y) where x == y:    print("x=y的點是(\(x), \(y))" );case let(x, y) where x == -y:    print("x=-y的點是(\(x), \(y))");case let (x, y):    print("其他的兩個點")}

另外還有continue,break,return,do-while,while,if語句都與其他語言類似

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【swift-總結】控制流程

相關文章

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.