Search code examples
swiftnsattributedstring

Swift: joined() for Array of NSAttributedString?


In Swift, you can join an Array of String like so:

let a = ["fee", "fi", "fo", "fum"]
print(a.joined(separator: " ")) // -> "fee fi fo fum"

How can I join an Array of NSAttributedString like this?


Solution

  • This extension adds the ability to join an Array of NSAttributedString, as you would with Strings.

    extension Array where Element: NSAttributedString {
      func joined(separator: NSAttributedString) -> NSAttributedString {
        guard let firstElement = first else { return NSAttributedString() }
    
        return dropFirst()
          .reduce(into: NSMutableAttributedString(attributedString: firstElement)) { collector, element in
            collector.append(separator)
            collector.append(element)
          }
      }
    
      func joined(separator: String = "") -> NSAttributedString {
        joined(separator: NSAttributedString(string: separator))
      }
    }