Swift: Attributed Strings Builder

Alexander Martirosov
Nov 2 · 1 min read

Here’s one way to create an attributed string in Swift:

It’s quite clean, but we still can reduce a boilerplate and improve scalability with a builder pattern. We’ll introduce a configurator, an object responsible for setting up and creating attributed strings. One instance of this configurator can be used to create all attributed strings with the same styling:

Method chaining is an expressive way to manipulate any object in object-oriented programming. Each method returns an object, allowing the calls to be chained together in a single statement. And it works especially well with a builder pattern.

A configurator or a builder is just a container that stores all properties of an attributed string. We set up this container with a set of methods that are chained together with dot notation. Think about it as a convenient way to say: Declare a "Hello, World" string with a standard font of size 16 pt, dark foreground color, line height of 28 pt and character spacing 0.2 .

Now let’s take a look at our configurator. The code below is its simplified version of and you can easily add new properties in a similar way.

If your project uses attributed strings extensively this solution will make your UI code more maintainable and much fun to read:)

That’s all! If you enjoyed the post don’t forget to like and follow:)

Stories. iOS Tutorial

MVC+C, Redux, SOA, DDD

Alexander Martirosov

Written by

IOS Developer

Stories. iOS Tutorial

MVC+C, Redux, SOA, DDD

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade