Combine versus Delegate pattern
When Swift was first released, it strongly urged protocol-oriented programming, which promoted the Delegate pattern. The way the delegate pattern works is one object would act on behalf of, or in coordination with, another object. In iOS development, delegate patterns have been used to handle events and user interactions for years.
That is, until reactive programming came into view, especially with Combine. We’ll do a simple comparison in playgrounds using Timer
so we can observe the evolution between the two.
How to do it...
We will start with a new playground:
- Create a new playground in Xcode. Go to File | New | Playground | iOS.
- On our first page, we’ll start with the Delegate approach. First, we’ll create our delegate protocol:
protocol TimerDelegate: AnyObject {
func timerEventReceived()
}
- Create a new class that will feed our delegate
timer
events:class TimerSender ...