✍️

SwiftのdoにもLabeled Statementsは書ける

2022/11/24に公開

前提

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 を使用してフローを制御できる。

lbl: do {
  if flag {
    continue lbl
  }
}

apple/swiftにテストも書いてある。

https://github.com/apple/swift/blob/1f3e159cfe518fbb723230a4e8f562248d34d863/test/SILGen/statements.swift#L384-L440

Labeled Statementsは無限ループの可能性やフローが読みづらくなったりと使用時には気をつけないといけない言語仕様だけど、製品コードでも使っているところはあった。

https://github.com/apple/swift/blob/1f3e159cfe518fbb723230a4e8f562248d34d863/stdlib/public/core/Unicode.swift#L572-L587

Discussion