Using Builder Pattern to Show Alert (iOS)

Nabin Shrestha
Towards Dev
Published in
2 min readFeb 4, 2022

--

I was googling around to learn about Builder Pattern and how can it be used in Swift. I went through few links that popped up on top of google search. After that I decided to implement the builder pattern to build and show alert in iOS application.

Let’s dive into how I did it.

  1. When creating an alert we normally need alert title, message, preferredStyle and action buttons which are normally success action and cancel action. So, let’s create 2 struct classes, one for holding UIAlertController properties and other one to hold UIAlertAction button properties.
AlertProperties
AlertActionProperties

2. Now, let’s create our AlertBuilder class as below:

a) We’ve passed viewController instance of whichever viewController we are going to create and show alert from in initializer.

b) We’ve created functions to pass the properties of alert as well as created onSuccess and onCancel closures to perform certain actions when user interacts with the buttons if needed.

3. Finally, let’s see how to use this on any needed view controller.

ViewController

In ViewController class I have just added a button in center. When the button is tapped we show our alert using AlertBuilder class. That’s it.

If this was helpful, feel free to show your appreciation by pressing on the clap 👏 button. Ciao. 😃

--

--