swift - 如何在比较中替换已弃用的 "--"前缀递减运算符?

标签 swift xcode int swift3 boolean

在我使用 --theX > 0 之前并且效果很好。

旧代码摘录:

if --theX < 0 {
    ...
if ++theX < 0 {
    ...
if ++theX > worldSize.width + 1  {
    ...
if --theX > worldSize.height  {
    ...

您可以在下面看到四行代码 theX - 1 > 0或类似的东西。现在我已经更新到 Swift 3,我认为只需更改 --theX 就很容易了。到 theX - 1theX -= 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 -= 1value += 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/

相关文章:

ios - 在设备上运行应用程序时查看本地数据库

ios - 多个完成 block 完成后执行的函数

ios - 无法使用 Facebook SDK 登录

Swift算法计算到达目的地的可能方式

ios - 缺少营销图标 Xcode bug?

c - 如何在 C 中将一个整数连接成一个字符串?

php - int 转成decimal 数据类型的过程?

ios - 线程 1 : EXC_BAD_ACCESS in Xcode with C code

ios - 在没有 1x 版本的情况下添加 @2x 和 @3x 图片

c++ - 三元运算符中的 Cout String 和 int