gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:24:07 27 4
gpt4 key购买 nike

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

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: , newSquarelet 定义在这个case陈述。 where正在使用 newSquare直接,似乎let部分首先执行,然后 where部分。这不是我对它的理解。谁能帮忙澄清一下?

最佳答案

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 绑定(bind)到 square + diceRoll 的值。
  • 评估 newSquare > finalSquare
  • 如果为真,则执行带有 newSquare 绑定(bind)的 block

这一行:

case finalSquare:

可以被认为是以下内容的简写:

case let __temp where __temp == finalSquare:

(没有创建真正的 __temp 符号)

关于swift - Swift语言中的switch语句,其中有where的case子句中的执行顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com