Swift 3.0 控制流

来源:互联网 发布:生死狙击刷矩阵要多久 编辑:程序博客网 时间:2024/06/05 06:29

一、循环
1、while循环 : 每次在循环开始时判断条件是否符合

var i = 0;while i < 10{    i += 1;}print(i);

输出结果: 10

2、repeat-while循环: 先执行一次循环的代码块。然后重复循环直到条件为false(至少循环一次)

var j = 0;repeat{    j += 1;}while j < 10print(j);

输出结果 : 10

3、for循环(Swift3.0 取消了传统的for循环结构)

for index in 1...5{     print("\(index) times 5 is \(index*5)");}/*1 times 5 is 52 times 5 is 103 times 5 is 154 times 5 is 205 times 5 is 25*/

如果你不需要区间序列内每一项的值,你可以使用下划线(_)替代变量名来忽略这个值

let base  = 3;let power = 10;var answer = 1;for _ in 1...power{    answer *= base;    // 3^n}

遍历字典

let dictionary:[String:Any] = ["name":"tom","age":18,"sex":"男"];for (key,value) in dictionary{    print("key:\(key) -> value:\(value)")    }

二、条件语句

1、 if-else和if-else if…-else

let  score = 74;if (score < 60){    print("及格");}else if (score >= 60 && score < 75){    print("及格");}else if (score >= 75 && score < 85){    print("良好");}else{    print("优秀");}

2、switch语句 : witch语句会尝试把某个值与若干个模式(pattern)进行匹配。根据第一个匹配成功的模式,switch语句会执行对应的代码。当有可能的情况较多时,通常用switch语句替换if语句。

2.1 复合匹配

let someCharacter: Character = "a"switch someCharacter {case "a","A": //为了让单个case同时匹配a和A,可以将这个两个值组合成一个复合匹配    print("The first letter of the alphabet")case "z":    print("The last letter of the alphabet")default:    print("Some other character")}//The first letter of the alphabet

备注: Swift 的switch语句比 C 语言中更加强大。在 C 语言中,如果某个 case 不小心漏写了break,这个 case 就会贯穿至下一个 case,Swift 无需写break,所以不会发生这种贯穿的情况。

2.2 区间匹配

let record = 75;switch record{case 0..<60:    print("成绩不合格");case 60..<75:    print("成绩合格");case 75..<85:    print("成绩良好");default:    print("优秀");}//成绩良好

2.3 switch结合元组(Touples)使用

let somePoint = (1, 1)switch somePoint {case (0, 0):    print("(0, 0) is at the origin")case (_, 0):    print("(\(somePoint.0), 0) is on the x-axis")case (0, _):    print("(0, \(somePoint.1)) is on the y-axis")case (-2...2, -2...2):    print("(\(somePoint.0), \(somePoint.1)) is inside the box")default:    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")}//on the x-axis with an x value of 2

2.3 switch 结合值绑定使用 : case 分支允许将匹配的值绑定到一个临时的常量或变量,并且在case分支体内使用 —— 这种行为被称为值绑定(value binding),因为匹配的值在case分支体内,与临时的常量或变量绑定。

let anotherPoint = (2, 0)switch anotherPoint {case (let x, 0):    print("on the x-axis with an x value of \(x)")case (0, let y):    print("on the y-axis with a y value of \(y)")case let (x, y):    print("somewhere else at (\(x), \(y))")}// 输出 "on the x-axis with an x value of 2"

2.4 switch 结合where

let yetAnotherPoint = (1, -1)switch yetAnotherPoint {case let (x, y) where x == y:    print("(\(x), \(y)) is on the line x == y")case let (x, y) where x == -y:    print("(\(x), \(y)) is on the line x == -y")case let (x, y):    print("(\(x), \(y)) is just some arbitrary point")}// 输出 "(1, -1) is on the line x == -y"

三、控制转移语句
1、coninue(继续 ) : 结束本次循环

var count = 0;for index in 1...5{    //求 1到10 内的奇数个数    if index % 2 == 0{        continue;    }    count += 1;}print(count);// 3

2、break (打断): 结束本次循环

var  runcount = 0;for (index,value) in [1,2,3,5,7,11].enumerated(){    if value % 3 == 0{        print("我找到被3整除的数了")        break;    }    runcount += 1;}print(runcount);/*   我找到被3整除的数了   2*/ 

3、through (贯穿): fallthrough关键字不会检查它下一个将会落入执行的 case 中的匹配条件。fallthrough简单地使代码继续连接到下一个 case 中的代码(注意:是下一个,不是整个)

var reCount = 10;switch reCount{case  0...10 :    print("case1");    fallthrough;case  15..<20:    print("case2");case  20..<45:    print("case3");default:    print("default");}/*case1case2*/

4、guard (提前结束): 如果guard语句的条件被满足,则继续执行guard语句大括号后的代码。如果条件不被满足,在else分支上的代码就会被执行。这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,break,continue或者throw做这件事,或者调用一个不返回的方法或函数

//定义一个函数func greet (dict: [String:String]){    guard dict["name"] != nil else{        return;    }    print(dict["name"] ?? "jack" );    guard dict["age"] != nil else{        print("the man of age unknow");        return;    }    print(dict["age"] ?? "19");}//调用函数greet(dict: ["name":"rose"]);/*rosethe man of age unknow*///调用函数greet(dict: ["name":"rose","age":"26"])/*rose26*/

四、检查API可用性
Swift内置支持检查 API 可用性,这可以确保我们不会在当前部署机器上,不小心地使用了不可用的API。编译器使用 SDK 中的可用信息来验证我们的代码中使用的所有 API 在项目指定的部署目标上是否可用。如果我们尝试使用一个不可用的 API,Swift 会在编译时报错。在它一般的形式中,可用性条件使用了一个平台名字和版本的列表。平台名字可以是iOS,macOS,watchOS和tvOS
例如:

if #available(iOS 5, *){   //在 iOS 使用 iOS 5 的 API}else{   //使用先前版本的 iOS 的 API}
0 0
原创粉丝点击