7.4 控制轉(zhuǎn)移語句

7.4 控制轉(zhuǎn)移語句

控制轉(zhuǎn)椅語句可以改變程序執(zhí)行的順序。Swift 提供了四種控制轉(zhuǎn)移語句:

  • continue
  • break
  • fallthrough
  • return

本章介紹了前三種語句,而return出現(xiàn)在第八章函數(shù)中。

Continue

continue用于循環(huán)中,程序執(zhí)行到continue時(shí),會(huì)返回當(dāng)前循環(huán)的最開始。就好像continue會(huì)對(duì)程序說:“當(dāng)前的循環(huán)已經(jīng)結(jié)束完成,進(jìn)行下一次吧”。

注意
for循環(huán)中,增量語句仍然會(huì)被執(zhí)行。

下面這段代碼從字符串中刪除了所有空格:

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
  if character == " " {
    continue
  }
  puzzleOutput += character
}
println(puzzleOutput)

如果循環(huán)當(dāng)前的字符是空格,就會(huì)進(jìn)入if執(zhí)行continue,此時(shí)程序會(huì)跳過后面的puzzleOutput += character而返回循環(huán)的開始。

Break

break語句會(huì)直接退出整個(gè)控制流。break可以用在switch語句或循環(huán)中。

用于循環(huán)中

當(dāng)程序執(zhí)行到break的時(shí)候,他會(huì)退出整個(gè)循環(huán),而不是返回循環(huán)的開始。就好像對(duì)程序說:“所有循環(huán)已經(jīng)結(jié)束,執(zhí)行后面的代碼吧”。

用于switch

Swift 的switch不允許情況的代碼段為空,但是有時(shí)候我們需要匹配某些情況,但是卻不執(zhí)行任何代碼,此時(shí)就是break的用武之地。
下面的例子將不同形式數(shù)字轉(zhuǎn)換成整數(shù)類型:

let numberSymbol: Character = "三"  // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "?", "一", "?":
    possibleIntegerValue = 1
case "2", "?", "二", "?":
    possibleIntegerValue = 2
case "3", "?", "三", "?":
    possibleIntegerValue = 3
case "4", "?", "四", "?":
    possibleIntegerValue = 4
default:
    break
}
if let integerValue = possibleIntegerValue {
    println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    println("An integer value could not be found for \(numberSymbol).")
}

Fallthrough

當(dāng)你需要switch使用類似 C 語言的穿越特性時(shí),就要用到此關(guān)鍵字了。

let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough
default:
    description += " an integer."
}
println(description)

這個(gè)例子中,我們用了fallthrough關(guān)鍵字。我們想輸出兩種字符串:"The number N is an integer" 或者 "The number N is a prime number, and also is an integer"。如果這個(gè)數(shù)字不是2,3,5,7,11,13,17,19中的一個(gè),那么根據(jù)程序的流程,就會(huì)得到第一種字符串;如果他是其中的一個(gè),就會(huì)進(jìn)入switch的第一中情況,該情況會(huì)將description變?yōu)?code>"The number N is a prime number, and also"。此時(shí)程序執(zhí)行到了fallthrough,他會(huì)忽略下一個(gè)情況的條件而執(zhí)行其代碼段。在本例中,程序會(huì)進(jìn)入默認(rèn)情況,在description后面添加" an integer"。

注意
使用fallthrough后,switch不會(huì)再檢測(cè)下一個(gè)情況的條件,而是直接進(jìn)入其代碼區(qū)域執(zhí)行。通過fallthrough進(jìn)入的情況不能帶有值綁定;同時(shí)已綁定的值在進(jìn)入的情況代碼區(qū)域中是不能使用的。

標(biāo)簽語句

我們可以在循環(huán)和switch中嵌套循環(huán)和switch,當(dāng)結(jié)構(gòu)復(fù)雜的時(shí)候,有時(shí)我們想continue外層的循環(huán)或者想break某層的switch這時(shí)就很不方便了。所以 Swift 引入了標(biāo)簽機(jī)制,來為循環(huán)和switch起名,同時(shí)continuebreak后面可以使用相應(yīng)的名字,來方便的控制程序流程。
標(biāo)簽語句是將標(biāo)簽的名字寫在行首,后面緊跟一個(gè)冒號(hào),之后是語句,以while循環(huán)為例:

LABEL_NAME: while 條件語句 {
  代碼區(qū)域
}

下面我們重新玩一次蛇形棋。我們要再改一下規(guī)則:

  1. 游戲開始時(shí),你把一個(gè)代表你的塑料小人放在1號(hào)格子左側(cè)的桌面上,這是0號(hào)格子的位置;
  2. 當(dāng)且僅當(dāng)你站在25號(hào)格子,你才勝利,否則執(zhí)行后面的步驟;
  3. 現(xiàn)在你擲骰子來獲取一個(gè)[1,6]之間的數(shù)字;
  4. 你沿著棋盤上數(shù)字增大的方向前進(jìn)該數(shù)字個(gè)格子,如果走過該數(shù)字的格子,你超出了棋盤范圍,那么返回第2個(gè)步驟。例如你現(xiàn)在在0號(hào)格子,擲骰子的數(shù)字是6,那么就前進(jìn)6步,停在6號(hào)格子上;如果現(xiàn)在在24號(hào)格子,就要重新擲骰子了。
  5. 現(xiàn)在看看腳下有沒有梯子,如果有,就沿著他爬到連接的格子;
  6. 重復(fù)執(zhí)行第2步。

我們用 Swift 來玩這個(gè)游戲:

let finalSquare = 25
var board = Int[](count: finalSquare + 1, repeatedValue: 0)
board[3] = 8
board[6] = 11
board[9] = 9
board[10] = 2
board[14] = -10
board[19] = -11
board[22] = -2
board[24] = -9

var square = 0
var turns = -1

gameLoop: while square != finalSquare {
    ++turns
    var diceRoll = turns % 6 + 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("You win after \(turns + 1) turns")

這段代碼中我們綜合使用了while循環(huán),switch的值綁定以及where子句。我們把turns設(shè)置為-1,在循環(huán)開始時(shí)進(jìn)行自增,這樣保證continue之后,turns`也會(huì)增加1。但是很不幸的是,在這種規(guī)則下,我們放置的梯子會(huì)使得你的塑料假人永遠(yuǎn)也走不到終點(diǎn),她會(huì)累死在這條蛇身上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容