Skip to content

Instantly share code, notes, and snippets.

@yurrriq
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save yurrriq/8828692cc400075d0cbd to your computer and use it in GitHub Desktop.

Select an option

Save yurrriq/8828692cc400075d0cbd to your computer and use it in GitHub Desktop.
join() for NSAttributedString

join() for NSAttributedString

String has it:

" and like ".join(["Like this", "that", "this, y'all."])
"Like this and like that and like this, y'all."

Why not NSAttributedString?

import Foundation

extension NSAttributedString {
  func join(sequence: [NSAttributedString]) -> NSAttributedString {
    if sequence.isEmpty { return NSAttributedString(string: "") }

    var acc = NSMutableAttributedString(attributedString: sequence[0])
    for elem in dropFirst(sequence) {
      acc.appendAttributedString(self)
      acc.appendAttributedString(elem)
    }
    return NSAttributedString(attributedString: acc)
  }
}
NSAttributedString(string: " and like ").join(
  ["Like this", "that", "this, y'all."].map({
    string -> NSAttributedString in
    let color = UIColor(
      red: CGFloat(drand48()),
      green: CGFloat(drand48()),
      blue: CGFloat(drand48()),
      alpha: 1.0)
    return NSAttributedString(
      string: string,
      attributes: [NSForegroundColorAttributeName: color])
  }))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment