sha sha - 2 months ago 9
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

Catch:

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 {
                r.appendAttributedString(separator)
            }
            r.appendAttributedString(e)
            return r
        }
    }

    func joinWithSeparator(separator: String) -> NSAttributedString {
        return joinWithSeparator(NSAttributedString(string: separator))
    }
}
Comments