《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 {

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值