Swift 语言中的 switch 语句,其中包含 where 的 case 子句中的执行顺序是什么?

switch statement in Swift language, what's the execution order in the case clause that has a where in it?

假设我们有以下伪代码片段:

switch some_variable {
    case let v where <condition_checking>:
        do_something...
}

据我了解,当代码执行进入 switch 时,它首先执行第一个 case 语句(我们只有一个)。然后它检查 condition_checking 部分,如果它是真的,那么 let 部分将被执行并且 do_something 将有机会 运行。对吗?

我问这个问题是因为我从 Apple 的文档中看到了下面的代码片段 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html(页面的最后一部分):

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

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!")

注意这条语句case let newSquare where newSquare > finalSquare:newSquare在这条case语句中由let定义。 where 直接使用 newSquare,似乎先执行 let 部分,然后再执行 where 部分。这不是我对它的理解。谁能帮忙解释一下?

首先,代码会将 expression 与大小写 pattern 匹配。在这种情况下是 let newSquare 然后它将执行 where 条件,这被称为 guard 表达式。

因此,将代码视为匹配大小写模式,然后使用 where 条件进一步验证。

首先:匹配大小写模式let newSquare,它只是将值赋给变量newSquare。

其次:检查guard表达式newSquare > finalSquare

A switch case can optionally contain a guard expression after each pattern. A guard expression is introduced by the keyword where followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If a guard expression is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the guard expression evaluates to true.

文档: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html

As I understand, when code execution goes into switch, it first goes with the first case statement (we only have one). Then it checks the condition_checking part and if it's true, then the let part will be execute and do_something will have a chance to run. Is that correct?

我想你误会了。在这段代码中:

case let newSquare where newSquare > finalSquare:

执行顺序为:

  • newSquare 绑定到 square + diceRoll 的值。
  • 评价newSquare > finalSquare
  • 如果为真,执行带有 newSquare 绑定的块

这一行:

case finalSquare:

可以被认为是 shorthand 因为:

case let __temp where __temp == finalSquare:

(没有创建真正的 __temp 交易品种)