Group Group Group Group Group Group Group Group Group

Singleton chapter use case

I’m at the singleton chapter and I would like to ask a quick question (I remember seeing the answer to this question previously but would like to double confirm and get a more elaborative answer from the community)

Consider an app, assume that the use case is there will ALWAYS only be 1 user logged in, is using currentUser as a singleton a bad design? Regardless of yes/no, why?

Hey @happiehappie

In the Singleton chapter of the Design Patterns by Tutorials book pay attention to the section with title What should you be careful about?:

Singletons are not appropriate if you’re simply trying to pass information from one view controller to another.
Instead, consider passing models via an initializer or property.

Considering the scenario where you only want to pass information of the current user with a Singleton the above quote makes sense

As additional info, John Sundell have a really good article
about singletons that might help you:
Avoiding singletons in Swift

Hope it helps!
Good luck :]

@happiehappie Thanks very much for your question!

One of the concerns with using Singletons is the fact that they are difficult to unit test, and also because they carry around state throughout the lifetime of the application. I personally would recommend using Dependency Injection instead, which would allow you to use a local variable that you can pass from a ViewController to a ViewController.

Singleton’s are popular because they offer a quick solution, but in the long term, they unfortunately can cause a lot of problems. For this reason, it is best to avoid them as much as possible.

I hope this helps!

All the best.

1 Like