Swift 学习-控制流(五)
2015-09-25 15:14
519 查看
l For in 遍历集合中元素
for index in1...5 {
print("\(index)times 5 is \(index * 5)")
}
如果你不需要知道区间内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:
let base = 3
let power = 10
var answer = 1
for _ in1...power {
answer *= base
}
print("\(base)to the power of \(power) is \(answer)")
// 输出 "3 tothe power of 10 is 59049"
l For 循环
格式定义如下:
for initialization; condition; increment { statements }
//index只在循序体内有效,如果要在外部访问则需要在外部声明。
for var index = 0; index < 3;++index
{
print("index is\(index)")
}
// index is 0
// index is 1
// index is 2
l while循环
格式定义如下:
while condition{ statement }
var st = 3
while st < 1
{
Print(“st:\(st)”)
st --
}
l Repeat-While(类似do-while) 循环
格式定义如下:
repeat { statements }while condition
let finalSquare = 25
var board = [Int](count:finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] =+09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] =-02; board[24] = -08
var square = 0
var diceRoll = 0
repeat {
// 顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
// 掷骰子 if ++diceRoll== 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
} while square < finalSquare
print("Game over!")
l if语句
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <=32
{
print("It's very cold. Consider wearing ascarf.")
}
//---------------
If .. {
}else if .. {
}else {
}
l 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
}
switch特点:
a) 不存在隐式的贯穿(No Implicit Fallthrough)
Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。这使得switch语句更安全、更易用,也避免了因忘记写break语句而产生的错误。
注意:虽然在Swift中break不是必须的,但你依然可以在
case 分支中的代码执行完毕前使用break跳出
b) 一个 case也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):
switch some value to consider {case value 1, value 2: statements }
c) 区间匹配
case 分支的模式也可以是一个值的区间
let approximateCount = 62
let countedThings = "moons orbitingSaturn"
var naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case12..<100:
naturalCount = "dozens of"
case100..<1000:
naturalCount= "hundreds of"
default:
naturalCount= "many"
}
print("There are \(naturalCount)\(countedThings).")
// 输出 "There are dozens of moonsorbiting Saturn."
d) 元组匹配
可以使用元组在同一个switch语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。
let approximateCount = 62
let countedThings = "moons orbitingSaturn"
varnaturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case1..<5:
naturalCount= "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case100..<1000:
naturalCount= "hundreds of"
default: naturalCount = "many"
}
print("There are \(naturalCount)\(countedThings).")
// 输出 "There are dozens of moonsorbiting Saturn."
e) 值绑定(ValueBindings)
case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为值绑定(value binding)。
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))")
}
// 输出 "on the x-axis with an xvalue of 2"
where
case 分支的模式可以使用where语句来判断额外的条件。
let yetAnotherPoint = (1, -1)
switchyetAnotherPoint {
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 arbitrarypoint")
}
// 输出 "(1, -1) is on the line x== -y"
l 控制转移语句(Control Transfer Statements)
Swift 有5中控制转移语句
1) break
立刻结束整个控制流的执行, 当在一个循环体中使用break时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。
Switch 语句中的break
当在一个switch代码块中使用break时,会立即中断该switch代码块的执行,并且跳转到表示switch代码块结束的大括号(})后的第一行代码。可以使用break来忽略某个分支。
2) continue
continue语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已经执行完了”,但是并不会离开整个循环体。
3) 贯穿(Fallthrough)
Swift 中的switch不会从上一个 case 分支落入到下一个 case 分支中。相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个switch代码块完成了它的执行。
如果需要 C 风格的贯穿的特性(不加break就会落入到下一个case分支中),你可以在每个需要该特性的 case 分支中使用fallthrough关键字。
let integerToDescribe = 5
var description = "The number \(integerToDescribe)is"
switch integerToDescribe {
case2,3,5,7,11,13,17,19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// 输出"The number 5 is a prime number, and also an integer."
4) return
结束语句的执行,立马返回到函数的调用出。
5) throw
抛出异常信息,代码中断执行。
l 带标签的语句
在循环嵌套的情况下,如果想中断或继续莫层的循环,标签会非常有用。
下面是while循环的定义例子,同样适用于其他循环语句。(Label name为标签名)
label name: while condition { statements }
let finalSquare = 25
var board = [Int](count: finalSquare + 1,repeatedValue: 0) board[03] = +08;
board[06] = +11; board[09] = +09;board[10] = +02
board[14] = -10; board[19] = -11;board[22] = -02;
board[24] = -08
var square = 0
var diceRoll = 0
gameLoop: while square != finalSquare{
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare: // 到达最后一个方块,游戏结束
break gameLoop
case let newSquare where newSquare >finalSquare:
// 超出最后一个方块,再掷一次骰子
continue gameLoop
default:
// 本次移动有效
square += diceRoll square += board[square]
}
}
print("Game over!")
sloop:for var i = 0; i < 10; ++i{
if i == 9{
print(“for is over”)
break sloop
}else{
print(“i\(i)”)
}
}
l 提前退出
guard(确保,保卫,保护)
像if语句一样,guard的执行取决于一个表达式的布尔值。我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分局中的代码。
//写法是这样的
guard condition else { statement }
func greet(person: [String: String]) {
guard let name = person["name"]else {
return
}
print("Hello \(name)")
guard let location =person["location"] else {
print("I hope the weather is nice nearyou.")
return
}
print("I hope the weather is nice in\(location).")
}
greet(["name":"John"])
// prints "Hello John!"
// prints "I hope the weather isnice near you."
greet(["name":"Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather isnice in Cupertino."
如果条件不被满足,在else分支上的代码就会被执行。这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,break或continue做这件事,或者它调用了一个不返回的方法或函数,例如fatalError()。
相比于可以实现同样功能的if语句,按需使用guard语句会提升我们代码的可靠性。 它可以使你的代码连贯的被执行而不需要将它包在else块中,它可以使你处理违反要求的代码接近要求。
for index in1...5 {
print("\(index)times 5 is \(index * 5)")
}
如果你不需要知道区间内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:
let base = 3
let power = 10
var answer = 1
for _ in1...power {
answer *= base
}
print("\(base)to the power of \(power) is \(answer)")
// 输出 "3 tothe power of 10 is 59049"
l For 循环
格式定义如下:
for initialization; condition; increment { statements }
//index只在循序体内有效,如果要在外部访问则需要在外部声明。
for var index = 0; index < 3;++index
{
print("index is\(index)")
}
// index is 0
// index is 1
// index is 2
l while循环
格式定义如下:
while condition{ statement }
var st = 3
while st < 1
{
Print(“st:\(st)”)
st --
}
l Repeat-While(类似do-while) 循环
格式定义如下:
repeat { statements }while condition
let finalSquare = 25
var board = [Int](count:finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] =+09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] =-02; board[24] = -08
var square = 0
var diceRoll = 0
repeat {
// 顺着梯子爬上去或者顺着蛇滑下去
square += board[square]
// 掷骰子 if ++diceRoll== 7 { diceRoll = 1 }
// 根据点数移动
square += diceRoll
} while square < finalSquare
print("Game over!")
l if语句
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <=32
{
print("It's very cold. Consider wearing ascarf.")
}
//---------------
If .. {
}else if .. {
}else {
}
l 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
}
switch特点:
a) 不存在隐式的贯穿(No Implicit Fallthrough)
Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用break语句。这使得switch语句更安全、更易用,也避免了因忘记写break语句而产生的错误。
注意:虽然在Swift中break不是必须的,但你依然可以在
case 分支中的代码执行完毕前使用break跳出
b) 一个 case也可以包含多个模式,用逗号把它们分开(如果太长了也可以分行写):
switch some value to consider {case value 1, value 2: statements }
c) 区间匹配
case 分支的模式也可以是一个值的区间
let approximateCount = 62
let countedThings = "moons orbitingSaturn"
var naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case12..<100:
naturalCount = "dozens of"
case100..<1000:
naturalCount= "hundreds of"
default:
naturalCount= "many"
}
print("There are \(naturalCount)\(countedThings).")
// 输出 "There are dozens of moonsorbiting Saturn."
d) 元组匹配
可以使用元组在同一个switch语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有可能的值。
let approximateCount = 62
let countedThings = "moons orbitingSaturn"
varnaturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case1..<5:
naturalCount= "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case100..<1000:
naturalCount= "hundreds of"
default: naturalCount = "many"
}
print("There are \(naturalCount)\(countedThings).")
// 输出 "There are dozens of moonsorbiting Saturn."
e) 值绑定(ValueBindings)
case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为值绑定(value binding)。
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))")
}
// 输出 "on the x-axis with an xvalue of 2"
where
case 分支的模式可以使用where语句来判断额外的条件。
let yetAnotherPoint = (1, -1)
switchyetAnotherPoint {
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 arbitrarypoint")
}
// 输出 "(1, -1) is on the line x== -y"
l 控制转移语句(Control Transfer Statements)
Swift 有5中控制转移语句
1) break
立刻结束整个控制流的执行, 当在一个循环体中使用break时,会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码。不会再有本次循环迭代的代码被执行,也不会再有下次的循环迭代产生。
Switch 语句中的break
当在一个switch代码块中使用break时,会立即中断该switch代码块的执行,并且跳转到表示switch代码块结束的大括号(})后的第一行代码。可以使用break来忽略某个分支。
2) continue
continue语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已经执行完了”,但是并不会离开整个循环体。
3) 贯穿(Fallthrough)
Swift 中的switch不会从上一个 case 分支落入到下一个 case 分支中。相反,只要第一个匹配到的 case 分支完成了它需要执行的语句,整个switch代码块完成了它的执行。
如果需要 C 风格的贯穿的特性(不加break就会落入到下一个case分支中),你可以在每个需要该特性的 case 分支中使用fallthrough关键字。
let integerToDescribe = 5
var description = "The number \(integerToDescribe)is"
switch integerToDescribe {
case2,3,5,7,11,13,17,19:
description += " a prime number, and also"
fallthrough
default:
description += " an integer."
}
print(description)
// 输出"The number 5 is a prime number, and also an integer."
4) return
结束语句的执行,立马返回到函数的调用出。
5) throw
抛出异常信息,代码中断执行。
l 带标签的语句
在循环嵌套的情况下,如果想中断或继续莫层的循环,标签会非常有用。
下面是while循环的定义例子,同样适用于其他循环语句。(Label name为标签名)
label name: while condition { statements }
let finalSquare = 25
var board = [Int](count: finalSquare + 1,repeatedValue: 0) board[03] = +08;
board[06] = +11; board[09] = +09;board[10] = +02
board[14] = -10; board[19] = -11;board[22] = -02;
board[24] = -08
var square = 0
var diceRoll = 0
gameLoop: while square != finalSquare{
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare: // 到达最后一个方块,游戏结束
break gameLoop
case let newSquare where newSquare >finalSquare:
// 超出最后一个方块,再掷一次骰子
continue gameLoop
default:
// 本次移动有效
square += diceRoll square += board[square]
}
}
print("Game over!")
sloop:for var i = 0; i < 10; ++i{
if i == 9{
print(“for is over”)
break sloop
}else{
print(“i\(i)”)
}
}
l 提前退出
guard(确保,保卫,保护)
像if语句一样,guard的执行取决于一个表达式的布尔值。我们可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分局中的代码。
//写法是这样的
guard condition else { statement }
func greet(person: [String: String]) {
guard let name = person["name"]else {
return
}
print("Hello \(name)")
guard let location =person["location"] else {
print("I hope the weather is nice nearyou.")
return
}
print("I hope the weather is nice in\(location).")
}
greet(["name":"John"])
// prints "Hello John!"
// prints "I hope the weather isnice near you."
greet(["name":"Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather isnice in Cupertino."
如果条件不被满足,在else分支上的代码就会被执行。这个分支必须转移控制以退出guard语句出现的代码段。它可以用控制转移语句如return,break或continue做这件事,或者它调用了一个不返回的方法或函数,例如fatalError()。
相比于可以实现同样功能的if语句,按需使用guard语句会提升我们代码的可靠性。 它可以使你的代码连贯的被执行而不需要将它包在else块中,它可以使你处理违反要求的代码接近要求。
相关文章推荐
- Apple Swift学习教程
- Swift中实现点击、双击、捏、旋转、拖动、划动、长按手势的类和方法介绍
- Swift中定义二维数组的方法及遍历方法示例
- Golang学习笔记(三):控制流
- 简单分析Swift语言的一些基本特征
- Swift与C语言指针结合使用实例
- Swift心得笔记之控制流
- 用Swift构建一个简单的iOS邮件应用的方法
- 苹果公司推出的新编程语言Swift简介和入门教程
- Swift中的指针操作和使用详细介绍
- Swift中使用正则表达式的一些方法
- Swift心得笔记之运算符
- Swift中使用可选类型完美解决占位问题
- Swift学习笔记之构造器重载
- Swift中的Access Control权限控制介绍
- Swift类型创建之自定义一个类型详解
- Swift教程之控制流详解
- 秒学Swift开发语言
- Swift专题讲解十七——Optional链