Is there a nicer way to do this?

53 views Asked by At

This is an extremely simple piece of code, but I feel like there is a more elegant way to do this:

    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

I feel like there should be a more elegant way to do the following using optional chaining maybe. I don't like the fact that

a) I'm checking if the value is equal to nil instead of using some kind of optional chaining

b) The line timeOfLastUpdate = currentTime is repeated twice.

Is there a better way to do this? Something more in line with Swift?

2

There are 2 answers

1
Duncan C On

How about this:

if timeOfLastUpdate = timeOfLastUpdate
{
  dt = currentTime - timeOfLastUpdate
}

timeOfLastUpdate = currentTime

If you need the code to return without running your "other code" in the case where "timeOfLastUpdate is nil, you might need to have your timeOfLastUpdate = currentTime assignment appear twice:

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

//other code here.
2
Duyen-Hoa On

How about this?

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