Swift教程之控制流详解

2020-01-08 22:47:32王旭

label name: while condition {
statements
}
下面的例子演示了如何使用标签语句以及嵌套的循环和switch。

 

依然采用之前的那个梯子与蛇的游戏,第一步依然是设置初始值:

 

复制代码
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循环与switch的嵌套来完成游戏

 

复制代码
gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
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!")

 

在这个代码中,将游戏的循环命名为gameLoop,然后在每一步移动格子时,判断当前是否到达了游戏终点,在break的时候,需要将整个游戏循环终止掉,而不是终止switch,因此用到了break gameLoop。同样的,在第二个分支中,continue gameLoop也指明了需要continue的是整个游戏,而不是switch语句本身。



注:相关教程知识阅读请移步到swift教程频道。