Reputation:
I am writing some helper functions for my Swift Project. I am not sure about 2 approaches and what's the pros/cons:
// use extension:
extension SKAction {
public static func blink(
count: Int,
outDuration: TimeInterval,
inDuration: TimeInterval,
chillDuration: TimeInterval) -> SKAction
{
var actions = [SKAction]()
for i in 0..<count {
let fadeOut = SKAction.fadeOut(withDuration: outDuration)
let fadeIn = SKAction.fadeIn(withDuration: inDuration)
actions += [fadeOut, fadeIn]
if chillDuration > 0 {
let wait = SKAction.wait(forDuration: chillDuration)
actions += [wait]
}
}
return SKAction.sequence(actions)
}
}
// use static util
public final class SKAnimationUtil {
public static func createBlinkAnimation(
count: Int,
outDuration: TimeInterval,
inDuration: TimeInterval,
chillDuration: TimeInterval) -> SKAction
{
var actions = [SKAction]()
for i in 0..<count {
let fadeOut = SKAction.fadeOut(withDuration: outDuration)
let fadeIn = SKAction.fadeIn(withDuration: inDuration)
actions += [fadeOut, fadeIn]
if chillDuration > 0 {
let wait = SKAction.wait(forDuration: chillDuration)
actions += [wait]
}
}
return SKAction.sequence(actions)
}
}
The static util is what I normally do before. But then I found that SKAction already come with lots of factory functions (e.g. SKAction.fadeIn(withDuration:)
).
Upvotes: 0
Views: 619
Reputation: 534885
First of all, declaring a class whose name starts with SK is illegal. Two-letter capital letter prefixes on type names are reserved for Apple! I like to start everything with My
to get around that rule.
OK, so on to the actual question: there is absolutely no significant difference between
extension SKAction {
public static func blink(
and
public final class SKAnimationUtil {
public static func createBlinkAnimation(
These are static methods, so they are effectively global, and the only reason for wrapping them in a type (SKAction or your utility class) is to namespace them in a nice way. (The static method is not using anything about its surrounding class.) The concept of "nice" is entirely subjective, so any further distinction would be a matter of opinion.
However, having said all that, I would just say that what I personally do is like the first example. What namespace "should" this method belong to? It is an SKAction factory, as you rightly say, so it can go nicely in SKAction. There is no reason to add to the existing stock of classes just to hold this method.
Consider, in particular, that the only reason for making a class is in order to instantiate that class. But you are never going to make an SKAnimationUtil instance, so Occam's Razor alone is enough to make one cry foul. This is not a helper in the classic sense.
Finally, I will just add that namespacing "holders" of static methods is best done, in Swift, using a struct or (even better nowadays) an enum. A class, even a final class, is way too much overhead for the job.
Upvotes: 4