gpt4 book ai didi

swift - 与 Swift Where 子句混淆。

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:58 26 4
gpt4 key购买 nike

所以我还在学习,但我很难理解这段代码的某个部分:

  case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop

为什么每次我运行循环时 newSquare 最终都是 27、28 和 29?

newSquare不应该每次都是0吗?我已经尝试在循环中打印出 newSquare,每次结果都是 27、28、29。

完整代码供引用:

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]
}
}
print("Game over!")

抱歉,我确定它很简单,但我不太明白:/

最佳答案

构造实际上不仅仅是:

case let newSquare where newSquare > finalSquare: // ...

...但是:

switch square + diceRoll {
// ...
case let newSquare where newSquare > finalSquare: // ...

switch语句评估 (square + diceRoll)并将其与订单中的所有指定案例进行比较。第一个是true获胜并取得执行控制权。

在此特定示例中,case let newSquare where newSquare > finalSquare每次 (square + diceRoll) > finalSquare 时都会“赢” ,就游戏逻辑而言,这意味着我们超出了棋盘限制。就地常量 newSquare在这里没有实际用处(即我们无论如何都不使用它的值)并且被引入只是为了能够使用 where switch-case 语句。

临时常数 newSquare通过所谓的 value binding 初始化:

A switch case can bind the value or values it matches to temporary constants, for use in the body of the case. This is known as value binding, because the values are “bound” to temporary constants within the case’s body.


顺便说一句,与示例中的内容几乎相同的另一种说法是:

switch square + diceRoll {
// ...
case finalSquare..<Int.max: // ...

... 如前所述 case finalSquare将处理我们最终恰好在最后一个正方形上的选项,而范围 finalSquare..<Int.max只会在之后进行评估,因此只会在 (square + diceRoll) 时触发大于 finalSquare .

关于swift - 与 Swift Where 子句混淆。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35445638/

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