2015-04-03 115 views
2

讓我們說,我們有以下的僞代碼片段: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:,在newSquarelet在此case語句中定義。 where直接使用newSquare,看起來let部分是第一次執行,然後是where部分。這不是我所瞭解的。任何人都可以幫助澄清嗎?

回答

3

據我瞭解,當代碼執行進入交換機時,它首先與第一個case語句去(我們只有一個)。然後它檢查condition_checking部分,如果它是真的,那麼let部分將被執行並且do_something將有機會運行。那是對的嗎?

我想你誤會了。在此代碼:

case let newSquare where newSquare > finalSquare: 

執行順序是:

  • 綁定newSquare到的square + diceRoll值。
  • 評估newSquare > finalSquare
  • 如果爲真,與newSquare結合

此行執行塊:

case finalSquare: 

可以被認爲是作爲簡寫:

case let __temp where __temp == finalSquare: 

(不創建一個真實的__temp符號)

+0

謝謝。非常清楚地解釋。令人困惑的是模式匹配部分只是創建一個變量。我現在很清楚。再次感謝! – 2015-04-03 18:48:33

3

首先,代碼將匹配expression與案例pattern。在這種情況下,它將是let newSquare它將執行where條件,該條件被稱爲guard表達式。

因此,將代碼視爲匹配案例模式,然後再使用where條件進行驗證。

第一個:匹配案例模式let newSquare,它將值簡單地分配給變量newSquare。

第二:檢查guard表達newSquare > finalSquare

開關情況下,可以任選地含有各 圖案之後的保護表達。關鍵字引入了一個警戒表達式,其中 後跟一個表達式,用於在案例中的某個模式被認爲與 控制表達式匹配之前提供附加的 條件。如果存在警戒表達式,則只有在控件 表達式的值與案例模式之一匹配並且警衛 表達式計算結果爲true時,纔會執行相關案例中的語句 。

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

+0

謝謝。 「提供**附加**條件」表示它在模式匹配後被評估。令人困惑的是模式匹配部分只是創建一個變量。哈哈我現在很清楚。再次感謝! – 2015-04-03 18:47:41

+0

是的,模式匹配只是簡單地分配一個變量是有點令人困惑,但他們這樣做是爲了始終匹配這種情況(如果第一種情況不符合),然後檢查「guard」where子句。這樣,如果它與where子句不匹配,它將在匹配案例模式時失敗並落入默認情況。 – chrissukhram 2015-04-03 20:08:10