服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Swift - Swift心得笔记之控制流

Swift心得笔记之控制流

2020-12-19 15:48Swift教程网 Swift

控制流(Control Flow)我不想这么译的。。。我更想叫控制语句,但是想想,这么叫也没错,意指流程控制。大部分用法跟C类似。

控制流基本上大同小异,在此列举几个比较有趣的地方。

switch

Break

文档原文是 No Implicit Fallthrough ,粗暴的翻译一下就是:不存在隐式贯穿。其中 Implicit 是一个经常出现的词,中文原意是:“含蓄的,暗示的,隐蓄的”。在 Swift 中通常表示默认处理。比如这里的隐式贯穿,就是指传统的多个 case 如果没有 break 就会从上穿到底的情况。再例如 implicitly unwrapped optionals ,隐式解析可选类型,则是默认会进行解包操作不用手动通过 ! 进行解包。

回到 switch 的问题,看下下面这段代码:

?
1
2
3
4
5
6
7
8
9
10
let anotherCharacter: Character = "a"
 
switch anotherCharacter {
case "a":
  println("The letter a")
case "A":
  println("The letter A")
default:
  println("Not the letter A")
}

可以看到虽然匹配到了 case "a" 的情况,但是在当前 case 结束之后便直接跳出,没有继续往下执行。如果想继续贯穿到下面的 case 可以通过 fallthrough 实现。

Tuple

我们可以在 switch 中使用元祖 (tuple) 进行匹配。用 _ 表示所有值。比如下面这个例子,判断坐标属于什么区域:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let somePoint = (1, 1)
 
switch somePoint {
case (0, 0):  // 位于远点
  println("(0, 0) is at the origin")
case (_, 0):  // x为任意值,y为0,即在 X 轴上
  println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):  // y为任意值,x为0,即在 Y 轴上
  println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2): // 在以原点为中心,边长为4的正方形内。
  println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
  println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
 
// "(1, 1) is inside the box"

如果想在 case 中用这个值,那么可以用过值绑定 (value bindings) 解决:

?
1
2
3
4
5
6
7
8
9
10
11
12
let somePoint = (0, 1)
 
switch somePoint {
case (0, 0):
  println("(0, 0) is at the origin")
case (let x, 0):
  println("x is \(x)")
case (0, let y):
  println("y is \(y)")
default:
  println("default")
}

Where

case 中可以通过 where 对参数进行匹配。比如我们想打印 y=x 或者 y=-x这种45度仰望的情况,以前是通过 if 解决,现在可以用 switch 搞起:

?
1
2
3
4
5
6
7
8
9
10
11
let yetAnotherPoint = (1, -1)
 
switch yetAnotherPoint {
case let (x, y) where x == y:
  println("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
  println("(\(x), \(y)) is on the line x == -y")
case let (x, y):
  println("(\(x), \(y)) is just some arbitrary point")
}
// "(1, -1) is on the line x == -y”

Control Transfer Statements

Swift 有四个控制转移状态:

continue - 针对 loop ,直接进行下一次循环迭代。告诉循环体:我这次循环已经结束了。
break - 针对 control flow (loop + switch),直接结束整个控制流。在 loop 中会跳出当前 loop ,在 switch 中是跳出当前 switch 。如果 switch 中某个 case 你实在不想进行任何处理,你可以直接在里面加上 break 来忽略。
fallthrough - 在 switch 中,将代码引至下一个 case 而不是默认的跳出 switch。
return - 函数中使用
其他

看到一个有趣的东西:Swift Cheat Sheet,里面是纯粹的代码片段,如果突然短路忘了语法可以来看看。

比如 Control Flow 部分,有如下代码,基本覆盖了所有的点:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
  if value == 1 {
    println("One!")
  } else {
    println("Not one!")
  }
}
 
// for loop (dictionary)
var dict = [
  "name": "Steve Jobs",
  "title": "CEO",
  "company": "Apple"
]
for (key, value) in dict {
  println("\(key): \(value)")
}
 
// for loop (range)
for i in -1...1 { // [-1, 0, 1]
  println(i)
}
// use .. to exclude the last number
 
// for loop (ignoring the current value of the range on each iteration of the loop)
for _ in 1...3 {
  // Do something three times.
}
 
// while loop
var i = 1
while i < 1000 {
  i *= 2
}
 
// do-while loop
do {
  println("hello")
} while 1 == 2
 
// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
  let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
  let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
  let vegetableComment = "Is it a spicy \(x)?"
default: // required (in order to cover all possible input)
  let vegetableComment = "Everything tastes good in soup."
}
 
// Switch to validate plist content
let city:Dictionary<String, AnyObject> = [
  "name" : "Qingdao",
  "population" : 2_721_000,
  "abbr" : "QD"
]
switch (city["name"], city["population"], city["abbr"]) {
  case (.Some(let cityName as NSString),
    .Some(let pop as NSNumber),
    .Some(let abbr as NSString))
  where abbr.length == 2:
    println("City Name: \(cityName) | Abbr.:\(abbr) Population: \(pop)")
  default:
    println("Not a valid city")
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

延伸 · 阅读

精彩推荐
  • SwiftSwift中排序算法的简单取舍详解

    Swift中排序算法的简单取舍详解

    对于排序算法, 通常简单的, 为大家所熟知的有, 选择排序, 冒泡排序, 快速排序, 当然还有哈希, 桶排序之类的, 本文仅比较最为常见的选择, 冒泡和快排,文...

    Castie111012021-01-10
  • Swift浅谈在Swift中关于函数指针的实现

    浅谈在Swift中关于函数指针的实现

    这篇文章主要介绍了浅谈在Swift中关于函数指针的实现,是作者根据C语言的指针特性在Swifft中做出的一个实验,需要的朋友可以参考下...

    Swift教程网4372020-12-21
  • SwiftSwift网络请求库Alamofire使用详解

    Swift网络请求库Alamofire使用详解

    这篇文章主要为大家详细介绍了Swift网络请求库Alamofire的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    lv灬陈强56682021-01-06
  • Swiftswift相册相机的权限处理示例详解

    swift相册相机的权限处理示例详解

    在iOS7以后要打开手机摄像头或者相册的话都需要权限,在iOS9中更是更新了相册相关api的调用,那么下面这篇文章主要给大家介绍了关于swift相册相机权限处...

    hello老文12682021-01-08
  • Swift详解Swift 之clipped是什么如何用

    详解Swift 之clipped是什么如何用

    这篇文章主要介绍了详解Swift 之clipped是什么如何用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下...

    iCloudEnd8532021-05-28
  • SwiftSwift 基本数据类型详解总结

    Swift 基本数据类型详解总结

    在我们使用任何程序语言编程时,需要使用各种数据类型来存储不同的信息。变量的数据类型决定了如何将代表这些值的位存储到计算机的内存中。在声明...

    Lucky_William4672021-12-26
  • Swift分析Swift性能高效的原因

    分析Swift性能高效的原因

    绝大多数公司选择Swift语言开发iOS应用,主要原因是因为Swift相比Objc有更快的运行效率,更加安全的类型检测,更多现代语言的特性提升开发效率;这一系...

    louis_wang9092021-01-16
  • SwiftSwift算法之栈和队列的实现方法示例

    Swift算法之栈和队列的实现方法示例

    Swift语言中没有内设的栈和队列,很多扩展库中使用Generic Type来实现栈或是队列。下面这篇文章就来给大家详细介绍了Swift算法之栈和队列的实现方法,需要...

    李峰峰10002021-01-05