Swift 3.0 学习笔记-4-控制流

Swift 3.0 学习笔记-4-控制流

标签(空格分隔): iOS Swift


前言:
swift3.0 学习笔记主要参考苹果开发者官网The Swift Programming Language (Swift 3.1)教程 以及 Swift 中文网
更纯粹的阅读的体验请移步至:
https://www.zybuluo.com/kakadee/note/726184



1. For-In Loops

使用for-in来遍历集合中的项目,比如数组的范围,排列中的项或者字符串中的字符。Swift 3.0 中已经移除了For-Condition-Increment的形式。
下面的例子打印了表中的5个元素

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 

如果不需要范围的值,可以用下划线替代变量名来忽略这些值:

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049" 

规定步长使用from:to:by:(不包含终点)

let minutes = 60
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}

另一种方式,使用from:through:by: (包含终点)

let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
    // render the tick mark every 3 hours (3, 6, 9, 12)
}

2. While Loops

while Loops的两种形式。

while condition {
    statements
}
repeat {
    statements
} while condition

3. Conditional Statements - 条件语句

If

没什么好说的。大家都会用

switch

switch some value to consider {
case value 1:
    respond to value 1
case value 2,
     value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}

注意:swift 3.0 中的switch语句和C中的不一样。break不是必须的,当然加上亦可。另一个区别就是当前一条case判断是空的话不会自动跳到下一条case判断语句

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// This will report a compile-time error.
// 这种情况下会报错

如果想让switch的一条判定同时满足多种情况,可以放在一起写,用逗号分隔即可。

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// Prints "The letter A"

范围匹配
switch中case的值可以检查他们内在的范围。这个例子使用数字范围可以提供任意大小数字的自然语言计数。

et approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."

元组
可以使用元组在相同的switch语句中测试多个值。每一个元组中的元素都可以试着和范围中不同的值进行匹配。另外,用下划线(_)标示符来匹配任意可能的值。

下面例子中使用一个点坐标(x,y),用元组型(Int, Int)来表示,可以在下面的图中分类出来:

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"

image_1bdvd5hcp11h41a1brue1kpl18vm9.png-17.9kB
Value Bindings 值绑定
一个switch的case能绑定用于匹配临时常量或变量值,在case的分支代码里使用。这就是value binding(值绑定),因为这些值在case的代码体中是临时常量或变量的“边界”。

下面的例子有一个点(x,y),用元组型(Int,Int)来表示,在图种展示出来如下:

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    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))")
}
// Prints "on the x-axis with an x value of 2"

Where

switch的case能使用where子句来进一步判断条件。 下面的例子将点(x,y)在下图种分类:

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")
}
// Prints "(1, -1) is on the line x == -y"

image_1bdvdclpm1oie1ndj1ecp69avorm.png-26.6kB
switch语句判断了点是否在绿色斜线上且x == y,或在紫色斜线上且x == -y,或都不是。

4. Control Transfer Statements - 控制转移语句

控制转移语句能改变已经执行代码的顺序,能使代码跳转到别的部分。Swift有四个句子:

  • continue
  • break
  • fallthrough
  • return

Continue
Continue语句告诉循环体终止现在的操作,然后开始迭代下一个循环。好像在说“我这次迭代做完啦”,总之不会离开循环体。

Break
Break语句能立即终止整个控制流。可以根据你想要的在switch或循环语句里的任何地方终止整个执行。

Fallthrough
Swift中的Switch不会掉下到case的下方并进入下一个case。因此,整个switch语句会在第一个匹配的case完成后结束。相反,C语言要求你在每个case的末尾插入一个break来防止掉入。相比于C语言,Swift的switch禁止默认掉入让更加简洁和可控,这样避免了执行多个case的错误。
如果你确实需要C式的掉入特性,你可以使用fallthrough关键词。

let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        description += " a prime number, and also" fallthrough
    default:
        description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer." 

Labeled Statements - 标签语句
你可以嵌套循环或在switch语句中嵌套其他的循环,Swift语句种的switch可以创建复杂的控制流结构。 然而,循环和switch语句都可以过早地使用break。因此,有时明确的使用break来终止代码很有用。类似的,如果你有多个嵌套的循环,continue会更有用。

为了做到这一点,你可以用statement label来标记循环或switch,与break或continue语句一起使用这个标签来终止或继续标记语句的执行。

label name: while condition {
    statements
}

这样,你就可以用这个标签来代替这个循环语句。

var count = 0;
countLoop : while count < 5 {
    count += 1;
    if (count == 3) {
        break countLoop
    }
}
print(count)
// 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值