我正在阅读Apple的Swift指南,我在do-while循环中遇到错误,我无法解决为什么Xcode会抛出错误。
本代码直接来自本书:
let finalSquare = 25
var board2 = [Int](count: finalSquare + 1, repeatedValue: 0) //26 values (0 included)
board2[03] = +08; board2[06] = +11; board2[09] = +09; board2[10] = +02 //the ladders
board2[14] = -10; board2[19] = -11; board2[22] = -02; board2[24] = -08 //the snakes
var square2 = 0
var diceRoll2 = 0
do {
square2 += board2[square2]
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2
} while square2 < finalSquare
但是我想在滚动后向上移动梯子或者直接向上移动蛇,所以我这样做了:
do {
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2
square2 += board2[square2]
} while square2 < finalSquare
这会引发错误:
Execution was interrupted, reason:EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
答案 0 :(得分:0)
在原始代码中:
do {
square2 += board2[square2]
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2
} while square2 < finalSquare
square2递增,然后检查其值finalSquare
,导致循环结束,如果它大于或等于。
代替您的代码:
do {
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2 // < incremented here
square2 += board2[square2] // < exception here
} while square2 < finalSquare
你增加square2
,然后你用它来访问相应的数组元素,但不检查它是否在数组边界后面(检查是在访问数组后完成的,所以在这种情况下没用)。
快速补丁是添加一个明确的检查:
do {
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2
if square2 < finalSquare {
square2 += board2[square2]
}
} while square2 < finalSquare
但如果以这种形式书写,它可能更具可读性:
do {
if ++diceRoll2 == 7 { diceRoll2 = 1 }
square2 += diceRoll2
if square2 < finalSquare {
square2 += board2[square2]
} else {
break
}
} while true
虽然我不是内心休息的无尽循环的忠实粉丝。