让我们说,我们有以下的伪代码片段:Swift语言中的switch语句,case子句中的执行顺序是什么?
switch some_variable {
case let v where <condition_checking>:
do_something...
}
据我了解,当代码执行进入交换机时,它首先与第一个case语句去(我们只有一个)。然后它检查condition_checking部分,如果它是真的,那么let部分将被执行并且do_something将有机会运行。那是对的吗?
我问这个问题,是因为我看到了下面的代码片段从苹果公司的文件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
由let
在此case
语句中定义。 where
直接使用newSquare
,看起来let
部分是第一次执行,然后是where
部分。这不是我所了解的。任何人都可以帮助澄清吗?
谢谢。非常清楚地解释。令人困惑的是模式匹配部分只是创建一个变量。我现在很清楚。再次感谢! – 2015-04-03 18:48:33