Nate Stedman

Joining Attributes

January 5th, 2016

Since the first release, Attributed has had a join() extension function for sequences of attributed-string-like values:

let attributedString = [
    "Unformatted ",
    UIColor.redColor().foregroundAttribute(["Red"]),
].join().attributedString

This allows for attribute-less portions in the final attributed string. In Attributed 0.3.0, the join() extension is added to sequences of attribute functions as well.

When all attributes must be nested individual, applying a number of attributes is harder to follow. For example, with a red foreground color, black background color, and single underline:

UIColor.redColor().foregroundAttribute(
    UIColor.blackColor().backgroundAttribute(
        NSUnderlineStyle.StyleSingle.attribute(
            "Content"
        )
    )
)

With the new join(), these attributes can be combined into a single function:

let attributes = [
    UIColor.redColor().foregroundAttribute,
    UIColor.blackColor().backgroundAttribute
    NSUnderlineStyle.StyleSingle.attribute
].join()

attributes("Content")

This makes it easy to repeatedly use the joined attributes, without repeating the nested structure:

UIFont.systemFontOfSize(12).attribute([
    attributes("Styled"),
    " Not Styled ",
    attributes("Styled")
].join())

Attributed is available on Github. I recommend using Carthage to integrate it with a project, by adding this line to your Cartfile:

github "natestedman/Attributed"