Shan Robertson
Shan Robertson

Reputation: 2742

swift efficiently reusing classes

I'm currently working on a game using swift and spritekit. I have a class called Utilities that has a bunch of generic functions that get used around the game. Currently I create a new instance of the Utilities class in my single game scene, and then pass the references though to other classes like so

self.util = Utilities()
self.player = Player(util: self.util)
self.monster = Monster(util: self.util)

I'm doing this so that i only create one instance of the class, but the more i go on the more just want to make a new instance of utilities in each class i need it in. Is there a downside to this? Is it more efficient to just have the one instance created and pass it around or will it not make a difference if i have say 5 or 6 instances?

Upvotes: 0

Views: 222

Answers (2)

hasen
hasen

Reputation: 166182

If the Utilities instance does not hold any specific state, then you probably don't need a class at all. Just define your functions as public global functions.

Swift is not Java. Functions can stand on their own. They don't need to be attached to a class.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

Upvotes: 0

Shamas S
Shamas S

Reputation: 7549

Ideally you shouldn't need to instantiate your Utilities class. You can write public functions in it and call those methods from where ever you like.

If you need to instantiate your class and would like to keep a single instance, you should go for singleton. You can create a singleton like

class Utilities {
    static let sharedInstance = Utilities()
}

And you can get the instance by calling Utilities.sharedInstance

Upvotes: 3

Related Questions