Swift 个人学习笔记 - 06: 控制流
本文章纯粹是中文版《The Swift Programming Language》的学习笔记,所以绝大部分的内容都是文中有的。本文是本人的学习笔记,不是正式系统的记录。仅供参考 以下还是有很多没看懂、不确定的地方,我会以“存疑”的注解指出。 在此感谢中文版翻译者,这极大地加快了 Swift 的学习速度。 本文地址:http://www.52php.cn/article/p-urcxxtit-d.html Reference:原版:The Swift Programming Language 这篇一部分其实就是各种基础了,有 Objective-C 的基础,这一小节绝大部分是不用看的。主要关注 switch 和 guard 就好
没什么新意的部分for - in没什么好讲的,忽略 whilewhile condition { ... } repeat { ... } while condition ifif ... { ... } else if ... { ... } else { ... }
switch基本格式switch anInt { case 1: ... case 2,3,4: // 这里与 C 是非常不一样的 ... // 每一行 case 的执行语句中至少要有一句话。实在没话说的话, // 就用一个 break 吧。在其他情况下,default 并不是必须的 default: ... } 个人感觉,如果你是 Swift 和 Objective-C 混用的话, 此外,case 后面的内容可以用前几章提到的区间来表示。 元组和 where 语句的使用Switch 可以使用元组。元祖中可以使用 “ 比如官方例子: 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") }
此外,case 最后面还可以加上花样,就是使用 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") }
guard在 Objectice-C 中,我们一般会使用 guard condition else { ... }
下一篇Swift 个人学习笔记 - 07: 函数 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |