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 and memory in iOS?
While a static class allows only static methods and and you cannot pass static class as parameter. A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.
In Singleton class, we create a single static type object of the class. Making the object static allows us to access the object using the class name. Here, we are accessing the fileObj object using the class name FileManager .
Class functions are dynamically dispatched and can be overridden by subclasses. Static functions are invoked by a class, rather than an instance of a class. These cannot be overridden by a subclass.
While a static class is generally initialized when it is first loaded and it will lead to potential class loader issues. Singleton Objects stored on heap while static class stored in stack. Singleton Objects can have constructor while Static Class cannot.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With