Can Swift Singleton be a class with purely class functions

It seems like the discussion stopped a couple of iterations of Swift back, but I'm curious that it was never suggested in the discussions (or, if that were the case, I never saw) that a singleton could just be a class with a pure class function, for example -

class MySingleton { private static var someVar: String? private static var someOtherVar: SomeType? class func start() { // etc... } class func doSomething() { // etc... } // etc, etc... } 

Are there any good reasons why we should not do this? I can’t come up with.

+5
source share
2 answers

If an object is never created, it is not single. There are no instances of an object, not just one instance.

There is nothing wrong with that, but what's the use?

EDIT

It seems to me that a real comparison occurs between a class that has only class methods and global functions.

In this comparison, the advantage that I see is the spacing between the names. When you create class methods, you must qualify function calls with the class name, so you can say

 SomeClass.someMethod() 

or

 SomeOtherClass.someMethod() 

These are two different functions, and it is obvious that they are different functions.

With global features you just talk

 someMethod() 

If in the future you generate code for another user who also has the global function someMethod() , you will get a compiler error about the duplicate function and must solve it.

0
source

What do you want to achieve?

In my experience, your approach is great if

  • you do not want to instantiate your class
  • you don’t care that someone can create an instance of your class (which does not have any advantages, but is still technically possible).
  • someVar and someOtherVar must always contain the same value for all instances.

Another approach is to have sharedInstance

 class MySingleton { private(set) static var sharedInstance = MySingleton() private var someVar: String? private var someOtherVar: SomeType? func start() { // etc... } func doSomething() { // etc... } // etc, etc... } 

This gives you great flexibility.

  • You can call MySingleton.sharedInstance.start() if you want to use a shared instance.
  • But, on the other hand, you can still create your own instance, for example let customInstance = MySingleton , with your own values ​​for someVar and someOtherVar .

So it really depends on what you want to achieve. If you want to be sure that no one can create another instance with their own vars, then your approach is safer than my alternative.

In this case, you might even think to make the final class, so no one can create a subclass that behaves differently.

0
source

Source: https://habr.com/ru/post/1274657/


All Articles