What is the best way using swift 4/iOS to handle asynchronous requests eg. to Firebase Database? [closed]

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/361237

  •  23-01-2021
  •  | 
  •  

Question

I've been using firebase database and now firestore for a while. I'm prob an intermediate level programmer and still at uni. I'm still a bit unsure re: the best way to handle calls that are occurring async to firebase database and updating the UI. I've previously used delegates to do this but I was wondering whether GCD and Dispatch.main.async - which I don't fully understand - are an alternative way.

Was it helpful?

Solution

GCD and Delegation solve different problems. Delegation is Apple's name for the Strategy Pattern while GCD is an API library for managing threads (updated below.) Because of this, your question doesn't make a whole lot of sense. There are plenty of situations where you would use both GCD and delegation.

My guess is that you are actually asking about Delegation vs passing closures as callbacks. I think the Swift community is still working out best-practices in this regard so it's hard to give any definite rules.

Generally though, I would say that:

  • If the Delegate would require an associated type (or using Any and casting), then a closure would probably be better. If the closure requires that an enum be passed with more than a couple of cases, then a delegate would be better.
  • If the Delegate would end up with only one method, then prefer a closure. If the closure must be passed as an @escaping parameter then prefer a Delegate.

The above are not mutually exclusive. Personal preference figures heavily here. In all cases, you want to cater to the needs of the code that provides the Delegate/closure. Whatever makes life easier for that code should be your guide.

EDIT

Josh Caswell has called me out on my lack of precision regarding GCD. Per Apple's documentation, GCD is a framework for "[executing] code concurrently on multicore hardware by submitting work to dispatch queues managed by the system."

However, he is wrong about the Delegation pattern being what is referred to when talking about a "Delegate" in Apple's descriptions. Equating Apple's delegates with the Strategy pattern is more correct.

Licensed under: CC-BY-SA with attribution
scroll top