Swift 个人学习笔记 - 06: 控制流

本文章纯粹是中文版《The Swift Programming Language》的学习笔记,所以绝大部分的内容都是文中有的。本文是本人的学习笔记,不是正式系统的记录。仅供参考

以下还是有很多没看懂、不确定的地方,我会以“存疑”的注解指出。

在此感谢中文版翻译者,这极大地加快了 Swift 的学习速度。

本文地址:https://segmentfault.com/a/1190000008440577


Reference:

原版:The Swift Programming Language
中文版:Swift 3 编程语言 - 控制流

这篇一部分其实就是各种基础了,有 Objective-C 的基础,这一小节绝大部分是不用看的。主要关注 switch 和 guard 就好

没什么新意的部分

for - in

没什么好讲的,忽略

while

    while condition {
        ...
    }
    
    repeat {
        ...
    } while condition

if

    if ... {
        ...
    } else if ... {
        ...
    } else {
        ...
    }

switch

基本格式

    switch anInt {
    case 1:
        ...
    case 2, 3, 4:      // 这里与 C 是非常不一样的
        ...            // 每一行 case 的执行语句中至少要有一句话。实在没话说的话,
                       // 就用一个 break 吧。在其他情况下,default 并不是必须的
    default:
        ...
    }

个人感觉,如果你是 Swift 和 Objective-C 混用的话,建议还是在每一个分支处理的结尾统一加上 break 语句。因为如果不这么做,你一不小心就会把 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")
    }

coordinateGraphSimple_2x.png

此外,case 最后面还可以加上花样,就是使用 where 语句进一步限制 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")
    }

coordinateGraphComplex_2x.png

guard

在 Objectice-C 中,我们一般会使用 if 在函数最开始进行参数检查。在 Swift 中,建议使用 guard 来做这样的事情。语法如下:

    guard condition else {
        ...
    }

下一篇

Swift 个人学习笔记 - 07: 函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值