---
title: "Adding string attributes slightly easier"
slug: adding-string-attributes-slightly-easier
section: tech
date: 2016-10-03T12:46:00.000Z
canonical: https://roland.leth.ro/blog/tech/adding-string-attributes-slightly-easier
---

Say we have a composed string that looks like this:

```swift
let date = "22 July, 2017"
let value = "€ 148"
let quantity = 5
let string = "\(quantity) of your items, in value of \(value), have been delivered on \(date)."
// 5 of your items, in value of € 148, have been delivered on 22 July, 2017.
```

It would be nice to emphasize the important bits, and the usual approach would be to create an `NSMutableAttributedString`, and to add the required attributes:

```swift
let attributedString = NSMutableAttributedString(
  string: string,
  attributes: [
      .font: UIFont.systemFont(ofSize: 14)
      .foregroundColor: UIColor.gray
  ]
)

attributedString.addAttributes(
  [
    .foregroundColor: UIColor.darkGray,
    .font: UIFont.boldSystemFont(ofSize: 15)
  ],
  range: (string as NSString).range(of: date)
)
attributedString.addAttributes(
  [
    .foregroundColor: UIColor.darkGray,
    .font: UIFont.boldSystemFont(ofSize: 15)
  ],
  range: (string as NSString).range(of: value)
)
attributedString.addAttributes(
  [
    .foregroundColor: UIColor.darkGray,
    .font: UIFont.boldSystemFont(ofSize: 15)
  ],
  range: (string as NSString).range(of: quantity)
)
```

That's a bit of a mouthful, if you ask me. `forEach` to the rescue!

```swift
let attributedString = NSMutableAttributedString(
  string: string,
  attributes: [
      .font: UIFont.systemFont(ofSize: 14)
      .foregroundColor: UIColor.gray
  ]
)

[date, value, quantity].forEach {
  attributedString.addAttributes(
    [
      .foregroundColor: UIColor.darkGray,
      .font: UIFont.boldSystemFont(ofSize: 15)
    ],
    range: (string as NSString).range(of: $0)
  )
}
```

Slightly more compact, and a bit easier to scan.

On a side note, I find it funny how `NS(Mutable)AttributedString` requires a `String`, and won't accept an `NSString` to init, but `addAttribute(s)` requires an `NSRange`. ¯\\\_(ツ)\_/¯