Swift学习笔记(10)——控制流

16 篇文章 0 订阅

划重点:Swift中Switch语句与其他语言的不同;guard语句

1. For-In 循环

(1)使用闭区间操作符(…)

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
// 区间操作符(...)表示的从15的数字区间。
// index被依次赋值为15

如果index是一个每次循环遍历开始时被自动赋值的常量。index在使用前不需要声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用let关键字声明。
(2)在循环体内没有用到区间序列内每一项的值,可以使用下划线(_)替代变量名来忽略这个值

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// 输出 "3 to the power of 10 is 59049"
// for _ in 1...power:只是做10次(power次)循环
// 完成功能:3的10次幂

(3)遍历数组元素
(4)遍历一个字典来访问它的键值对。字典的每项元素会以(key, value)元组的形式返回。使用显式的常量名称来解读(key, value)元组。

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs
// (animalName, legCount):字典的键(key)解读为常量animalName,字典的值会被解读为常量legCount
// 因为字典是无序的,所以遍历出来的元素也是无序的

2. While 循环

在条件为true时循环。

Swift 提供两种while循环形式:

  • while循环,每次在循环开始时计算条件是否符合;
  • repeat-while循环,每次在循环结束时计算条件是否符合。

(一) While

while循环从计算一个条件开始。如果条件为true,会重复运行一段语句,直到条件变为false。
下面是 while 循环的一般格式:

while condition {
statements
}

(二)Repeat-While

和while的区别:在判断循环条件之前,先执行一次循环的代码块。然后重复循环直到条件为false。(和其他语言中的do-while循环是类似的。)

repeat-while循环的一般格式:

repeat {
statements }
while condition

3.条件语句

Swift 提供两种类型的条件语句:if语句和switch语句。

Switch与其他语言的有所不同
(1) 与 C 和 Objective-C 中的switch语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。所以,break语句是不必须的
如果需要 C 风格的贯穿的特性,你可以在每个需要该特性的 case 分支中使用fallthrough关键字。

……
let i=1
var description = "The number \(i) is"

switch i {
case 1:
    description += " a number, and also"
fallthrough  
// 在匹配这个case之后,继续执行后面casedefault的分支,fallthrough关键字不会检查它下一个将会落入执行的 case 中的匹配条件,只是使代码继续连接到下一个 case 中的代码。

default:
    description += " an integer."
}
print(description)
// 输出 "The number 1 is a number, and also an integer."

(2)switch语句不会一起匹配”a”和”A”。
(3)可以让单个case同时匹配多个条件,用逗号隔开。
(4)case 分支的模式也可以是一个值的区间
像下面的:

……
case 0:
    naturalCount = "no"
case 1..<5:
naturalCount = "a few"
……

(5)我们可以使用元组在同一个switch语句中测试多个值。元组中的元素可以是值,也可以是区间。
用下划线(_)来匹配所有可能的值
例子:

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):   // (1,1)在这个区间内,输出这个case里面的语句
    print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// 输出 "(1, 1) is inside the box"

如果存在多个匹配,那么只会执行第一个被匹配到的 case 分支。
(6)值绑定(Value Bindings)
case 分支允许将匹配的值绑定到一个临时的常量或变量,并且在case分支体内使用

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):  
    // case (let x, 0):将匹配一个纵坐标为0的点,并把这个点的横坐标赋给临时的常量x
    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))")

// 这个switch语句不包含默认分支。因为case let(x, y):声明了一个可以匹配余下所有值的元组。这使得switch语句已经完备了,因此不需要再书写默认分支。
}
// 输出 "on the x-axis with an x value of 2"

(7)Where
case 分支的模式可以使用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"

这三个 case 都声明了常量x和y的占位符,用于临时获取元组yetAnotherPoint的两个值。这两个常量被用作where语句的一部分,从而创建一个动态的过滤器(filter)。
当且仅当where语句的条件为true时,匹配到的 case 分支才会被执行。
(8)复合匹配
当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case后面,并且用逗号隔开。当case后面的任意一种模式匹配的时候,这条分支就会被匹配。

4. 控制转移语句

Swift 有五种控制转移语句:

  • continue
  • break
  • fallthrough
  • return
  • throw

(1)Continue和Break
continue语句:告诉一个循环体立刻停止本次循环,重新开始此循环体的下次循环。
Break:立刻中断该循环体的执行。

(2)带标签的语句
break或者continue加标签,来结束或者继续这条被标记语句的执行。
while循环体的标签语法,同样的规则适用于所有的循环体和条件语句。

label name: while condition { statements }

(3)guard语句
与if语句的比较:

func doSometing(str:String?)
{
   Let v:String?=str
   If v==nil  //如果要判断的情况很多,即if里面的代码很长,可以返回错误情况
   {
      return
   }
   //use v to do someting
}
func doSometing(str:String?)
{
//如果条件v=str不为真(即str不是一个String型,是nil),则执行else里面的“return”来退出guard语句
   Guard let v=str else{  
      return
   }
   //如果条件为真,则执行这里的语句
   //use v to do someting
}

具体说明:
像if语句一样,guard的执行取决于一个表达式的布尔值
一个guard语句总是有一个else从句,如果条件不为真则执行else从句中的代码。else这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,break,continue或者throw做这件事,或者调用一个不返回的方法或函数,例如fatalError()。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值