标签语句作为引导关键词在标签的同一行,后面跟着冒号“:”。 这里有一个用了该符号的while循环例子,所有的循环和switch都是相同的。
复制代码
<label name>: while <condition> {
<statements>
}
下面的例子里有一个用了标签的while循环,使用了break和continue语句,Snakes and Ladders游戏可以在上文中看到:
为了胜利,你必须恰好到达25号方块
如果骰子带你超过了25号方块,你必须重新丢骰子直到正好抵达25号方块。
游戏板和上文中的一样
变量 finalSquare, board, square, diceRoll的初始化都跟前文一样:
复制代码
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语句来实现游戏逻辑。While循环的标签为gameLoop,为Snakes and Ladders Game标记出游戏主体。
While循环的条件是while square != finalSquare,意思是你必须落在25号方块上:
复制代码
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









