![]() ![]() SWIFT SHARE SINGLETON THROUGHOUT PROJECT CODEThis will make your code far more robust and testable. Instead of accessing the static methods of your singleton you can inject a NetworkProvider object into the class in the constructor that uses it. You will want to use classes, or structs with non static functions because when something isn't a singleton you can use dependency injection. If you then find yourself with many Service objects, you can combine these objects with a facade pattern, that groups functionality when appropriate for a given View/ViewModel. Why not just have a NetworkManager object that you initialize?Įven better why not separate out the services into a few logical classes? One service per class may get a bit arduous, but if you think critically you will likely be able to group services together appropriately. I would recommend thinking carefully about using a singleton. This seems to be an extremely common way of handling networking in iOS and Swift probably because it is very simple to reason about a single global singleton object for services. You can, and should, always solve the problem using dependency injection. That might sound a bit strict, but the drawbacks of singletons outweigh the little benefits of taking the shortcut. There are many articles online which try to answer the question: “when is it ok to use a singleton?”
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |