✍️
SwiftのdoにもLabeled Statementsは書ける
前提
Swift言語ではLabeled Statementsという言語仕様で、ループや条件文に対してLabelをつけて制御することができる。
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!")
本題
doはループ制御じゃないのにラベルをつければ continue
を使用してフローを制御できる。
- goto文的な使い方
lbl: do {
if flag {
continue lbl
}
}
apple/swiftにテストも書いてある。
Labeled Statementsは無限ループの可能性やフローが読みづらくなったりと使用時には気をつけないといけない言語仕様だけど、製品コードでも使っているところはあった。
Discussion