0

I have not found myself using a singleton in a while because I get all the functionality of one from the static class. Are there any differences between the two that I should be aware of?

Singleton Example:

class SomeManager {
    static let sharedInstance = SomeManager()
    var user: User!
    init(user: User) {
        self.user = user
    }
}

With usage:

SomeManager.sharedInstance.user

Static Class Example:

class SomeManager {
    static var user: User!
    init(user: User) {
        SomeManager.user = user
    }
}

With usage:

SomeManager.user

I know the obvious difference is that one is an entire class being made static, and the other is declaring specific parts (that are desired to be from a single instance) static. Is there any reason to use one over the other.

I have one setup for my Network right now where I have a singleton class of network calls that are accessed through a bunch of static methods in a class that does nothing but contain the Network singleton and its static methods. I find this to have the appropriate scope for my scenario, but have not done enough research to guarantee the quality of the method.

Example:

class NetworkCalls {
    static let network = Network()

    static func getToken(completion: () -> Void) {
        network.apiGetToken() {
            completion()
        }
    }
}

With usage:

NetworkCalls.getToken() {
    print("Network Call Completed")
}

It works fine, so I am only looking for matters of efficiency, things to think about, and differences between this and alternative methods. Any tips/advice would be highly appreciated!

Sethmr
  • 3,046
  • 1
  • 24
  • 42
  • 1
    Possible duplicate of [Difference between static function and singleton class in swift](http://stackoverflow.com/questions/37806982/difference-between-static-function-and-singleton-class-in-swift). – Martin R Dec 27 '16 at 17:15

1 Answers1

0

I may be wrong, but the idea of a singleton is to get a unique single class avaliable for all the application, which is only initialized once in a life time (most cases) and used mostly for state validations during the lifetime of your app.

A static class is more general use kind of class.

Althought you can do the same with a static class...

LearningCharlito
  • 327
  • 1
  • 2
  • 20