HiveBrain v1.2.0
Get Started
← Back to all entries
patternswiftMinor

Calculating delta in SpriteKit using Swift

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
swiftspritekitcalculatingusingdelta

Problem

I am attempting to learn swift by refactoring one of my old games and I need to rewrite my update method which calculates a delta time. This code works but is ugly. How would I go about properly rewriting this?

import SpriteKit

class GameScene: SKScene {
    var lastUpdateTimeInterval: CFTimeInterval?

    override func update(currentTime: CFTimeInterval) {

        var delta: CFTimeInterval?
        if let luti = lastUpdateTimeInterval {
            delta = currentTime - luti
        } else {
            delta = currentTime
        }

        lastUpdateTimeInterval = currentTime;

        if (delta > 1.0) {
            delta = minTimeInterval;
            lastUpdateTimeInterval = currentTime;
        }

        updateWithTimeSinceLastUpdate(delta!)
    }
}

Solution


  • You are inconsistent with the optional semicolons. It's optional in Swift, but all the example code I've seen from Apple excludes them. They may be excluding them simply to drive home the point that they're not necessary, but it will probably end up being standard to exclude them. Either way, you've included them in 3 lines and excluded them in 5. Consistency is actually more important then what "best practice" says to do, and your code isn't consistent in this regard.



  • In Swift, the parenthesis around if statements are optional. Like the semicolons, you've been inconsistent in this. You include the parenthesis once and omit them once. Again, all the example code I've seen from Apple omits them and that will probably become the Swift standard, but again, what's most important is consistency.



  • Perhaps in an effort to force some Swift into your code, you've needlessly declared delta as an optional. There's no possible path through this method which results in delta being uninitialized, and that becomes pretty evident when we force unwrap it as we pass it to an argument expecting a non-optional.



  • updateWithTimeSinceLastUpdate() is probably copied over from a method that looks like this in ObjC: updateWithTimeSinceLastUpdate:, which might be okay. It's a method called update that takes a variable which describes the timeSinceLastUpdate, right? In Swift, the method might be a bit Swift-ier if timeSinceLastUpdate is actually the name of the argument: update(timeSinceLastUpdate:delta). This makes it more clear. The part outside the parenthesis describes what the method actually does, while the part inside the method describes what sort of arguments to send.

Context

StackExchange Code Review Q#56966, answer score: 5

Revisions (0)

No revisions yet.