Difference between static function and singleton class in swift

Sunil Sharma picture Sunil Sharma · Jun 14, 2016 · Viewed 9.3k times · Source

I want to create a class where all utility methods will be kept and these methods will be used throughout the app.
Problem:1
Is it good to create a singleton class and keep all necessary methods there or should I create a class where all function will be static.
Problem:2
What is main difference between above two approaches in swift ?
Problem:3
How it will impact performance in iOS?

Answer

kandelvijaya picture kandelvijaya · Jun 14, 2016

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.