# Calculating delta in SpriteKit using Swift

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!)
}
}

• I'm not completely certain refactoring old, existing, working code into a language that doesn't yet even allow for access modifiers is the best of ideas, particularly not when the new language can use stuff written in the old language, meaning you can use the new stuff with the old stuff without rewriting any of the new stuff. Jul 14, 2014 at 23:45
• This was more of a way to learn swift. Of course this wouldn't be optimal in a professional environment I know that swift/objc can live together in the same project. The could of course doesn't need to be written in the same manor. How would you go about calculating a delta in a "swift" way? Jul 15, 2014 at 19:56

2. 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.
3. 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.
4. 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.