Difference between static function and singleton class in swift [closed]

Sure this sounds confusing and can be debated. However, from the best practices i can put some suggestions.

Singleton is usually used to create a resource intensive and one timer initialisation for instance: a database connector, login handler and such.

Utility class are classes that only have static functions and variables. It should not deal with async task and expensive resource handling like opening a database connector.

In your case, if the utility is doing some resource intensive process its better to wrap in a singleton. If not, then Static functions in a class is better in my opinion. This is so also because, Swift will dispatch all static functions in a class using static dispatch. Whereas this cannot be true in Singleton although Swift likes to optimizes.

Static Dispatch are 4 times faster than Dynamic Dispatch as far as Objective-C runtime is used. This is true for swift too. However, it only takes 4 nano seconds to dispatch Dynamiclly.

I hope this makes you clear.

Leave a Comment