《swift2.0 官方教程中文版》 第2章-05控制流


import Foundation


/*For 循环**************************************************************/

//你可以使用 for-in 循环来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字 符。

for index in 1...5 {

print("\(index) times 5 is \(index * 5)")

}

//上面的例子中,index 一个每次循环遍历开始时被自动赋值的常量。这种情况下,index 在使用前不需要声 ,只需要将它包含在循环的声明中,就可以对其进行隐式声明,而无需使用 let 关键字声明。


//如果你不需要知道区间内每一项的值,你可以使用下划线( _ )替代变量名来忽略对值的访问

let base = 3

let power = 3

var answer = 1

for _ in 1...power {

answer *= base

}

print("\(base) to the power of \(power) is \(answer)")


//使用 for-in 遍历一个数组所有元素:

let names = ["Anna","Alex","Brian","Jack"]

for name in names {

print("Hello,\(name)!")

}


//你也可以通过遍历一个字典来访问它的键值对。遍历字典时,字典的每项元素会以 (key,value) 元组的形式返 ,你可以在 for-in 循环中使用显式的常量名称来解读 (key,value) 元组,遍历是无序的

let numberOfLegs = ["spider":8,"ant":6,"cat":4]

for (animalName,legCount) in numberOfLegs {

print("\(animalName)s have \(legCount) legs")

}


//除了 for-in 循环,Swift 提供使用条件判断和递增方法的标准 C 样式 for 循环:

for var index = 0; index < 3; ++index {

print("index is \(index)")

}


//下面是一般情况下这种循环方式的格式:

//for initialization ; condition ; increment { statements }

// C 语言中一样,分号将循环的定义分为 3 个部分,不同的是,Swift 不需要使用圆括号将“initialization; condition; increment”包括起来。




/*While 循环**************************************************************/

//下面是一般情况下 while 循环格式:

//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

//

//while square < finalSquare {

// // 掷骰子

// if ++diceRoll == 7 { diceRoll = 1 } // 根据点数移动

// square += diceRoll

// if square < board.count {

// // 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去

// square += board[square]

// }

// print("位置是\(square)")

//}

//print("Game over!")



//while 循环的另外一种形式是 repeat-while,它和 while 的区别是在判断循环条件之前,先执行一次循环的代 码块,然后重复循环直到条件为 false

//注意: Swift语言的 repeat-while 循环合其他语言中的 do-while 循环是类似的。

//下面是一般情况下 repeat-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 {

// // 顺着梯子爬上去或者顺着

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...