Builder pattern in Swift

Kumar Reddy
2 min readJun 30, 2019

--

As an iOS developer whenever we try to do styling the UILabel, most of the times will look in the project for the same kind of code and will copy-paste the code with little modification as desired for the needs.

This will produce a lot of boilerplate code and hard for modifications. In addition to that, it will take a bit of developer time to test the code every time you write.

Okay. Let’s get into the problem first and then will dive into the best ways to solve the problem.

I have the following simple text and I expected to style the label according to the requirement shown in the picture.

let sampleText = "This is a about styling the label using the builder pattern, so we can be more productive and easy way to style the label. No more boilerplate code"

Expected output

If I go with the typical approach, the code looks like the below. It is more error-prone and introduces close to 40 lines of code. More lines mean more testing required.

With new styling using builder pattern, you will end up writing 10 lines of code which is easy to understand, crisp and clear.

Here is the snapshot of the Label style builder. You can write more func set(_:) ->LabelStyleBuilder functions which you use more frequently in your project.

You can find the full source code here. https://github.com/BKRApps/LabelStylingExample

--

--

Kumar Reddy
Kumar Reddy

Written by Kumar Reddy

Mobile Engineering Manager @ KeepTruckIn | Ex — PayPal, Swiggy | https://github.com/BKRApps.

No responses yet