Delegation Pattern in Swift

Tram Ho

As we get started with Swift and iOS , we will see the familiar word Delegate , which can be clearly seen in Apple’s frameworks. UITableView and UICollectionView are the most concrete examples of delegation in Swift. In this article, we will learn what delegate pattern is and how to implement it in Swift.

Delegation pattern is a messaging design pattern in Swift, used in one-to-one communication between objects, taking advantage of the Swift protocol to delegate to an object.

Let’s look at a simple example by creating a simple view

We have a class called BubbleView . Now define a delegate by writing a protocol

Please note that both Apple naming is Delegate at the end and methods in the “didDo” format.

Back to the class view, we now add a new property

Notice here we use weak for the new property . This avoids the possibility of having a retain cycle as can be seen below

Here we want the view controller have a bubble view that can handle all UI interactions, such as touching a bubble view . It can be seen that this is an MVC with a separate view and separate controller

That’s it, above is an example of a delegation – handling events that touch the user’s view, by delegating the logic to the controller.

Hopefully, you will understand and feel comfortable using Delegate Pattern . The first article has many shortcomings, hope everyone helps.


Chia sẻ bài viết ngay

Nguồn bài viết : Viblo