在Swift中叫倍,可以在其他循環(huán)和條件語句中嵌套循環(huán)和條件語句枣抱,以創(chuàng)建復(fù)雜的控制流結(jié)構(gòu)。 然而蚊惯,循環(huán)和條件語句都可以使用break語句來提前結(jié)束它們的執(zhí)行魂仍。 因此,有時(shí)需要明確關(guān)于哪個(gè)循環(huán)或條件語句希望break語句終止拣挪。 類似地擦酌,如果您有多個(gè)嵌套循環(huán),那么可以顯式地說明continue語句應(yīng)該影響哪個(gè)循環(huán)菠劝。
要實(shí)現(xiàn)這些目標(biāo)赊舶,您可以使用語句標(biāo)簽標(biāo)記循環(huán)語句或條件語句。 使用條件語句,可以使用帶有break語句的語句標(biāo)簽來結(jié)束帶標(biāo)簽語句的執(zhí)行笼平。 使用循環(huán)語句园骆,可以使用帶有break或continue語句的語句標(biāo)簽來結(jié)束或繼續(xù)執(zhí)行帶標(biāo)簽的語句。
標(biāo)簽語句通過將標(biāo)簽放置在與語句的介紹器關(guān)鍵字相同的行上寓调,后跟冒號(hào)來指示锌唾。 下面是一個(gè)while循環(huán)語法的例子,所有循環(huán)和switch語句的原理是相同的
*label name*: while *condition* {
*statements*
}
let finalSquare = 25
var board = [Int](repeating: 0, count: finalSquare + 1)
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 {
diceRoll += 1
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]
}
}
print("Game over!")
如果上面的break語句沒有使用gameLoop標(biāo)簽夺英,它會(huì)斷開switch語句晌涕,而不是while語句。 使用gameLoop標(biāo)簽可以清楚地知道應(yīng)該終止哪個(gè)控制語句痛悯。
當(dāng)調(diào)用continue gameLoop跳轉(zhuǎn)到循環(huán)的下一次迭代時(shí)余黎,不一定非要使用gameLoop標(biāo)簽。 游戲中只有一個(gè)循環(huán)载萌,因此對(duì)于哪個(gè)循環(huán)continue語句會(huì)產(chǎn)生影響惧财,沒有歧義。 但是扭仁,使用帶有continue語句的gameLoop標(biāo)簽沒有任何危害垮衷。 這樣做與標(biāo)簽在break語句旁邊的使用一致,有助于使游戲的邏輯更清晰地閱讀和理解乖坠。