The Swift Programming Language-官方教程精译Swift(6)控制流--Control Flow
Swift提供了类似C语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行不同代码分支的if和switch语句,还有控制流程跳转到其他代码的break和continue语句。
for index in ... {
println("\(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 =
let power =
var answer =
for _ in ...power {
answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049
这个例子计算 base 这个数的 power 次幂(本例中,是 3 的 10 次幂),从 1 (3 的 0 次幂)开始做 3 的乘法, 进行 10 次,使用 0 到 9 的半闭区间循环。这个计算并不需要知道每一次循环中计数器具体的值,只需要执行了正确的循环次数即可。下划线符号 _ (替代循环中的变量)能够忽略具体的值,并且不提供循环遍历时对值的访问。
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
你也可以通过遍历一个字典来访问它的键值对(key-value pairs)。遍历字典时,字典的每项元素会以 (key, value)元组的形式返回,你可以在 for-in 循环中使用显式的常量名称来解读 (key, value)元组。下面的例子中,字典的键(key)解读为常量 animalName ,字典的值会被解读为常量 legCount :
let numberOfLegs = ["spider": , "ant": , "cat": ]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
// spiders have 8 legs
// ants have 6 legs
// cats have 4 legs
字典元素的遍历顺序和插入顺序可能不同,字典的内容在内部是无序的,所以遍历元素时不能保证顺序。更多数组和字典相关内容,查看集合类型章节。
for character in "Hello" {
println(character)
}
// H
// e
// l
// l
// o
for var index = ; index < ; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
for initialization; condition; increment {
statements
}
initialization
while condition {
statements
increment
}
var index: Int
for index = ; index < ; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
println("The loop statements were executed \(index) times")
// prints "The loop statements were executed 3 times
while condition {
statements
}
let finalSquare =
var board = Int[](count: finalSquare + , repeatedValue: )
一些方块被设置成有蛇或者梯子的指定值。梯子底部的方块是一个正值,是你可以向上移动,蛇头处的方块是一个负值,会让你向下移动:
board[] = +; board[] = +; board[] = +; board[] = +
board[] = -; board[] = -; board[] = -; board[] = -
var square =
var diceRoll =
while square < finalSquare {
// roll the dice
if ++diceRoll == { diceRoll = }
// move by the rolled amount
square += diceRoll
if square < board.count {
// if we're still on the board, move up or down for a snake or a ladder
square += board[square]
}
}
println("Game over!")
do {
statements
} while condition
let finalSquare =
var board = Int[](count: finalSquare + , repeatedValue: )
board[] = +; board[] = +; board[] = +; board[] = +
board[] = -; board[] = -; board[] = -; board[] = -
var square =
var diceRoll =
do-while 的循环版本,循环中第一步就需要去检测是否在梯子或者蛇的方块上。没有梯子会让玩家直接上到第 25 个方格,所以玩家不会通过梯子直接赢得游戏。这样在循环开始时先检测是否踩在梯子或者蛇上是安全的。
do {
// move up or down for a snake or ladder
square += board[square]
// roll the dice
if ++diceRoll == { diceRoll = }
// move by the rolled amount
square += diceRoll
} while square < finalSquare
println("Game over!")
var temperatureInFahrenheit =
if temperatureInFahrenheit <= {
println("It's very cold. Consider wearing a scarf.")
}
// prints "It's very cold. Consider wearing a scarf."
temperatureInFahrenheit =
if temperatureInFahrenheit <= {
println("It's very cold. Consider wearing a scarf.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// prints "It's not that cold. Wear a t-shirt."
显然,这两条分支中总有一条会被执行。由于温度已升至40华氏度,不算太冷,没必要再围围巾——因此,else分支就被触发了。
temperatureInFahrenheit =
if temperatureInFahrenheit <= {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= {
println("It's really warm. Don't forget to wear sunscreen.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// prints "It's really warm. Don't forget to wear sunscreen."
在上面的例子中,额外的if语句用于判断是不是特别热。而最后的else语句被保留了下来,用于打印既不冷也不热时的消息。
temperatureInFahrenheit =
if temperatureInFahrenheit <= {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= {
println("It's really warm. Don't forget to wear sunscreen.")
}
switch `some value to consider` {
case `value `:
`respond to value `
case `value `,
`value `:
`respond to value or `
default:
`otherwise, do something else`
}
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
println("\(someCharacter) is a consonant")
default:
println("\(someCharacter) is not a vowel or a consonant")
}
// prints "e is a vowel"
在这个例子中,第一个case块用于匹配五个元音,第二个case块用于匹配所有的辅音。
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// this will report a compile-time error
不像C语言里的switch语句,在 Swift 中,switch语句不会同时匹配"a"和"A"。相反的,上面的代码会引起编译期错误:case "a": does not contain any executable statements——这就避免了意外地从一个case块贯穿到另外一个,使得代码更安全、也更直观。
switch `some value to consider` {
case `value `,
`value `:
`statements`
}
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case :
naturalCount = "no"
case ...:
naturalCount = "a few"
case ...:
naturalCount = "several"
case ...:
naturalCount = "tens of"
case ...:
naturalCount = "hundreds of"
case ...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way."
let somePoint = (, )
switch somePoint {
case (, ):
println("(0, 0) is at the origin")
case (_, ):
println("(\(somePoint.0), 0) is on the x-axis")
case (, _):
println("(0, \(somePoint.1)) is on the y-axis")
case (-..., -...):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
// prints "(1, 1) is inside the box"
let anotherPoint = (, )
switch anotherPoint {
case (let x, ):
println("on the x-axis with an x value of \(x)")
case (, let y):
println("on the y-axis with a y value of \(y)")
case let (x, y):
println("somewhere else at (\(x), \(y))")
}
// prints "on the x-axis with an x value of 2"
let yetAnotherPoint = (, -)
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")
}
// prints "(1, -1) is on the line x == -y"
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput += character
}
}
println(puzzleOutput)
// prints "grtmndsthnklk"
在上面的代码中,只要匹配到元音字母或者空格字符,就调用continue语句,使本次循环迭代结束,从新开始下次循环迭代。这种行为使switch匹配到元音字母和空格字符时不做处理,而不是让每一个匹配到的字符都被打印。
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
possibleIntegerValue: Int?
switch numberSymbol {
case "", "?", "一", "?":
possibleIntegerValue =
case "", "?", "二", "?":
possibleIntegerValue =
case "", "?", "三", "?":
possibleIntegerValue =
case "", "?", "四", "?":
possibleIntegerValue =
default:
break
}
if let integerValue = possibleIntegerValue {
println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
println("An integer value could not be found for \(numberSymbol).")
}
// prints "The integer value of 三 is 3."
这个例子检查numberSymbol是否是拉丁,阿拉伯,中文或者泰语中的1...4之一。如果被匹配到,该switch分支语句给Int?类型变量possibleIntegerValue设置一个整数值。
let integerToDescribe =
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case , , , , , , , :
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."
这个例子定义了一个String类型的变量description并且给它设置了一个初始值。函数使用switch逻辑来判断integerToDescribe变量的值。当integerToDescribe的值属于列表中的质数之一时,该函数添加一段文字在description后,来表明这个是数字是一个质数。然后它使用fallthrough关键字来"落入"到default分支中。default分支添加一段额外的文字在description的最后,至此switch代码块执行完了。
label name: while condition {
statements
}
let finalSquare =
var board = Int[](count: finalSquare + , repeatedValue: )
board[] = +; board[] = +; board[] = +; board[] = +
board[] = -; board[] = -; board[] = -; board[] = -
var square =
var diceRoll =
这个版本的游戏使用while循环体和switch方法块来实现游戏的逻辑。while循环体有一个标签名gameLoop,来表明它是蛇梯棋游戏的主循环。
gameLoop: while square != finalSquare {
if ++diceRoll == { diceRoll = }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
square += diceRoll
square += board[square]
}
}
println("Game over!")
每次循环迭代开始时掷骰子。与之前玩家掷完骰子就立即移动不同,这里使用了switch来考虑每次移动可能产生的结果,从而决定玩家本次是否能够移动。
The Swift Programming Language-官方教程精译Swift(6)控制流--Control Flow的更多相关文章
- The Swift Programming Language-官方教程精译Swift(1)小试牛刀
通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”.在 Swift 中,可以用一行代码实现: println("hello, world") 如果你 ...
- The Swift Programming Language-官方教程精译Swift(9) 枚举-- --Enumerations
枚举定义了一个通用类型的一组相关的值,使你可以在你的代码中以一个安全的方式来使用这些值. 如果你熟悉 C 语言,你就会知道,在 C 语言中枚举指定相关名称为一组整型值.Swift 中的枚举更加灵活 ...
- The Swift Programming Language-官方教程精译Swift(8)闭包 -- Closures
闭包是功能性自包含模块,可以在代码中被传递和使用. Swift 中的闭包与 C 和 Objective-C中的 blocks 以及其他一些编程语言中的 lambdas 比较相似. 闭包可以捕获和存储其 ...
- The Swift Programming Language-官方教程精译Swift(7)函数 -- Functions
函数 函数是执行特定任务的代码自包含块.通过给定一个函数名称标识它是什么,并在需要的时候使用该名称来调用函数以执行任务. Swift的统一的功能语法足够灵活的,可表达任何东西,无论是不带参数名称的简单 ...
- The Swift Programming Language-官方教程精译Swift(5)集合类型 -- Collection Types
Swift语言提供经典的数组和字典两种集合类型来存储集合数据.数组用来按顺序存储相同类型的数据.字典虽然无序存储相同类型数据值但是需要由独有的标识符引用和寻址(就是键值对). Swift语言里的数 ...
- The Swift Programming Language-官方教程精译Swift(4)字符串和字符
String 是一个有序的字符集合,例如 "hello, world", "albatross".Swift 字符串通过 String 类型来表示,也可以表示为 ...
- The Swift Programming Language-官方教程精译Swift(3)基本运算符
运算符是检查, 改变, 合并值的特殊符号或短语. 例如, 加号 + 把计算两个数的和(如 let i = 1 + 2). 复杂些的运行算包括逻辑与&&(如 if enteredDoor ...
- The Swift Programming Language-官方教程精译Swift(2)基础知识
Swift 的类型是在 C 和 Objective-C 的基础上提出的,Int是整型:Double和Float是浮点型:Bool是布尔型:String是字符串.Swift 还有两个有用的集合类型,Ar ...
- 一群牛人翻译:The Swift Programming Language 中文版
无聊闲逛GIthub,看到一群牛人在github上创建了一个关于Switf的文档翻译项目 The Swift Programming Language 中文版 项目地址:中文版 Apple 官方 Sw ...
随机推荐
- QtQuick桌面应用程序开发指南 4)动态管理Note对象_B 5)加强外观 6)许多其他的改进
4.2.2 Stateless(不管状态)JavaScript库 为了让开发轻松点, 使用一个JavaScript接口来和数据库交互是个好主意, 它在QML中提供了方便的方法; 在QtCreator中 ...
- [Unity3d]定义自己的鼠标
[Unity3d]自己定义鼠标 我们在用unity3d开发自己的游戏的时候.自己定义游戏中的鼠标也是常常要用到的.那我就得学学.事实上原理非常easy,先将鼠标给隐藏,然后在鼠标的位置上画出一个自己定 ...
- 【翻译自mos文章】rman 备份时报:ORA-02396: exceeded maximum idle time
rman 备份时报:ORA-02396: exceeded maximum idle time 參考原文: RMAN backup faling with ORA-02396: exceeded ma ...
- ios新开发语言swift 新手教程
http://gashero.iteye.com/blog/2075324 视频教程:http://edu.51cto.com/lesson/id-26464.html
- Spring Framework 下载链接_现在有空
下载链接:http://repo.spring.io/libs-release-local/org/springframework/spring/ 点击打开链接 包括Spring的各个版本号: 3.2 ...
- SQL Server BCP使用小结
原文:SQL Server BCP使用小结 用法: bcp {dbtable ) );GO--输出XML格式化文件--说明一下:-t","是指定字段分隔符,稍后我们会讲到exe ...
- 兼容的网页宽度margin padding
hack兼容: -moz- /* Firefox 4 */ -webkit- /* Safari 和 Chrome */ -o- /* Opera */ IE6承认*和_和+,不承认!import ...
- 杭州电 1203 I NEED A OFFER!
I NEED A OFFER! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- 3D数学学习笔记——笛卡尔坐标系
本系列文章由birdlove1987编写.转载请注明出处. 文章链接: http://blog.csdn.net/zhurui_idea/article/details/24601215 1.3D数学 ...
- js中frame的操作问题
这里以图为例,在这里把frame之间的互相操作简单列为:1变量2方法3页面之间元素的互相获取. A 首先从 父(frameABC)------->子(frameA,frameB,frameC) ...