Swift: Attributed Strings Builder
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:)

