Swift 我的学习笔记 - 06: 控制流

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

如下仍是有不少没看懂、不肯定的地方,我会以“存疑”的注解指出。编程

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

本文地址:http://www.javashuo.com/article/p-qinmwcjc-hm.htmlsegmentfault


Reference:

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

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

没什么新意的部分

for - in

没什么好讲的,忽略ide

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 可使用元组。元祖中可使用 “_” 来表示 “*” 的含义。ui

好比官方例子:

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: 函数

相关文章
相关标签/搜索