sha sha - 1 year ago 74
Swift Question

Is there joinWithSeparator for attributed strings

Array of strings can be joined together with specific separator using joinWithSeparator method.

let st = [ "apple", "pie", "potato" ]
st.joinWithSeparator(", ")

As a result we will have "apple, pie, potato".

What if I have attributed strings inside my array? Is there easy way to combine them into one big attributed string?

Answer Source


import Foundation

extension SequenceType where Generator.Element: NSAttributedString {
    func joinWithSeparator(separator: NSAttributedString) -> NSAttributedString {
        var isFirst = true
        return self.reduce(NSMutableAttributedString()) {
            (r, e) in
            if isFirst {
                isFirst = false
            } else {
            return r

    func joinWithSeparator(separator: String) -> NSAttributedString {
        return joinWithSeparator(NSAttributedString(string: separator))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download