讓我們說,我們有以下的僞代碼片段: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