Why i cant use singletons? Why it is bad design pattern?

Hello, I have folowed this tutorial https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2 and was really happy about whole idea… I build an app which uses similar flow. There are three viewControllers and which of them uploads particular photo. (in the begging i call dispatchGroup.enter() in the singleton 3 times)Then i get results i notify my Repository and call dispatchGroup.leave(). Then I call it 3 times i send notification and open last viewcontroller…. This is really good separation of concerns, because my singleton acts as a Repository (i am coming from Android word) and we use that there. However I start to doubt that it is correct way of building complex apps… Would not it be better to create delegates in each one of viewcontrollers and after receiving response my last viewcontroller would conform to that delegate and would now if it is already a time to call function… I would not need dispatchGroup then, because I could just write lots of if statements… please help, me, why creating singleton as common source of truth across all VC is called bad practise?

Just bought a book and renewed my subscribtion…I like this community I am just confused about mvvm pattern in Ios… it is shame… in android it is much easier… you just use mvvm with repository and you will be fine. ViewModel provides data to Repository which then sends network requests and viewmodel subscribes to that observable…

Hi @wellbranding, I wouldn’t necessarily that singletons are either good or bad. This is something that I’ve seen other devs blog about but I do believe there could be a smart way of approaching singletons. For example, if we have this singleton

class Recipe {
    static let shared = Recipe()

    private init() { }

    func do(_ message: String) {
        print(message)
    }
}

Then we can use it as Recipe.shared.log(). Another way to go about this could be,

protocol Cooking {
    func do(_ message: String)
}
extension Cooking {
    func do(_ message: String) {
        Recipe.shared.do(message)
    }
}

Then we can create any type and conform to Cooking and call Do openly.

struct MainScreen: Cooking {
    func making() {
        do("Recipe used!")
    }
}

let screen = MainScreen()
screen.making()

This is an example as an alternative to using Singletons but again everyone may have different thoughts about it. Hope this helps!

Best,
Gina

This topic was automatically closed after 166 days. New replies are no longer allowed.