【问题标题】:Is there a nicer way to do this?有没有更好的方法来做到这一点?
【发布时间】:2015-06-09 19:29:59
【问题描述】:

这是一段极其简单的代码,但我觉得有一种更优雅的方式来做到这一点:

    if timeOfLastUpdate == nil {
        timeOfLastUpdate = currentTime
        return
    }

    //"Infinitesimal" moment of time used to update the position of the orbiter
    let dt:CFTimeInterval = currentTime - timeOfLastUpdate!
    timeOfLastUpdate = currentTime

    //Other code

我觉得应该有一种更优雅的方式来使用可选链接来执行以下操作。我不喜欢这样的事实

a) 我正在检查值是否等于 nil 而不是使用某种可选链接

b) timeOfLastUpdate = currentTime 行重复两次。

有没有更好的方法来做到这一点?更符合 Swift 的东西?

【问题讨论】:

  • timeOfLastUpdate 是否以 nil 开头?如果你可以消除 nil 检查的必要性,你就不需要做任何你认为不优雅的事情。现在,第一次调用此代码时,您只需设置 timeOfLastUpdate 即可跳过增量时间,但不应该有增量时间吗?轨道器启动和首次调用之间的时间差?
  • @WillM。好吧, timeOfLastUpdate 应该表示自上次调用“更新”函数以来的时间。如果这是第一次被调用,“timeOfLastUpdate”将是未定义的,不是吗?因此,无。如果你说增量时间应该是轨道器添加到场景和第一次“更新”之间的差异,我真的不能这样做,因为轨道器是由 SKS 编辑器添加到场景中的,而不是通过我的代码.
  • 您不希望第一次调用更新函数来做点什么吗?就像进行第一次更新一样,基于进度开始和第一次调用更新之间发生的事情。现在,你只是在浪费时间,就像从未发生过一样。
  • @WillM。 “在进度开始和第一次更新调用之间”是什么意思?更新的呼唤不就是进步的开始吗?这是每帧调用的第一件事,不是吗?
  • 进步的开始可能是一个错误的选择。我看不到您的所有代码,但必须触发更新循环,对吗?这就是我的意思。假设您在 t = 0 开始更新循环,然后第一次调用更新发生在 t=1,就目前而言,您只需将 lastUpdatedTime 设置为 1 并返回,忽略 t=0 和 t=1 之间的时间。

标签: ios swift coding-style


【解决方案1】:

这个怎么样:

if timeOfLastUpdate = timeOfLastUpdate
{
  dt = currentTime - timeOfLastUpdate
}

timeOfLastUpdate = currentTime

如果您需要在“timeOfLastUpdate 为零”的情况下返回代码而不运行“其他代码”,您可能需要让您的 timeOfLastUpdate = currentTime 分配出现两次:

if timeOfLastUpdate = timeOfLastUpdate
{
  dt = currentTime - timeOfLastUpdate
  timeOfLastUpdate = currentTime
  return
}
else
{
  timeOfLastUpdate = currentTime
}

//other code here.

【讨论】:

  • 恐怕这不是等价的。注意 return 语句是他的代码。
【解决方案2】:

这个怎么样?

if let _timeOfLastUpdate = timeOfLastUpdate, let dt = currentTime - _timeOfLastUpdate {
    //other codes
}

//if this line of code can be placed after "//other codes", cause I see it must be placed before //other codes
timeOfLastUpdate = currentTime 

【讨论】:

  • 这里的问题是“其他代码”很长,所以我不想把它放在if语句中。
  • 你可以把//其他代码放在一个函数中,然后在这个地方调用这个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 2011-03-10
  • 1970-01-01
  • 2015-06-15
相关资源
最近更新 更多