【问题标题】:How to replace the deprecated "--" prefix decrement operator in comparisons?如何在比较中替换已弃用的“--”前缀减量运算符?
【发布时间】:2017-05-12 06:02:21
【问题描述】:

在我使用--theX > 0 之前,它运行良好。

旧代码摘录:

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

您可以在下面看到具有theX - 1 &gt; 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'” ---> 使用 -= 或 += 时)。如果你们想知道,这是一个 Snake 街机游戏,上面的函数是当蛇移动(左、右、上、下)时发生的情况

对于为什么会发生此问题或可能如何使用不同但相似版本的增量和减量(- 和 ++)的任何帮助?

【问题讨论】:

  • 请用更有用的标题更新您的问题,具体到您遇到的问题。
  • 你在哪一行得到了这个错误?

标签: swift xcode int swift3 boolean


【解决方案1】:

语句--theX 正在使用预减运算符。它会在使用 theX 之前递减它的值,所以:

这个:

if --theX > 0 {
}

相当于:

theX -= 1
if theX > 0 {
}

其他人也是如此。如果您使用的是预减量 (--value) 或预增量 (++value),请在下一行使用 value 之前将其替换为 value -= 1value += 1


您将if --theX &gt; 0 转换为if theX - 1 &gt; 0 的问题是theX 的值没有被修改,因此当您在中构造Point 时,您将使用错误的theXreturn Point(x: theX, y: theY) 声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多