在我使用 --theX > 0
之前并且效果很好。
旧代码摘录:
if --theX < 0 {
...
if ++theX < 0 {
...
if ++theX > worldSize.width + 1 {
...
if --theX > worldSize.height {
...
您可以在下面看到四行代码 theX - 1 > 0
或类似的东西。现在我已经更新到 Swift 3,我认为只需更改 --theX
就很容易了。到 theX - 1
或 theX -= 1
.
尝试更新代码:
func move(_ point:Point, worldSize:WorldSize) -> (Point) {
var theX = point.x
var theY = point.y
switch self {
case .left:
if theX - 1 < 0 {
// theX = worldSize.width - 1
print("g.o.")
stopped = true
}
case .up:
if theY + 1 < 0 {
// theY = worldSize.height - 1
print("g.o.")
stopped = true
}
case .right:
if theX + 1 > worldSize.width + 1 {
// theX = 0
print("g.o.")
stopped = true
}
case .down:
if theY - 1 > worldSize.height {
// theY = 0
print("g.o.")
stopped = true
}
}
return Point(x: theX, y: theY)
}
}
但是,这似乎不起作用(“无法将‘Bool’类型的值转换为预期的参数类型‘Int’”---> 使用 -= 或 += 时)。如果你们想知道,这是一个蛇街机游戏,上面的函数是当蛇移动(左、右、上、下)时发生的事情
对于为什么会发生此问题或可能如何使用不同但相似版本的递增和递减(-- 和++)有何帮助?
最佳答案
--theX
语句使用了预递减运算符。它在使用之前递减 theX
的值,因此:
这个:
if --theX > 0 {
}
相当于:
theX -= 1
if theX > 0 {
}
其他人也是如此。如果您使用的是预递减 (--value
) 或预递增 (++value
),则将其替换为 value -= 1
或 value += 1
在下一行使用 value
之前。
将 if --theX > 0
翻译成 if theX - 1 > 0
的问题在于 theX
的值是未被修改,因此当您在 return Point(x: theX, y: theY) 中构造
语句。Point
时,您将使用错误的 theX
值
关于swift - 如何在比较中替换已弃用的 "--"前缀递减运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353830/