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?
This extension adds the ability to join an Array
of NSAttributedString
, as you would with String
s.
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))
}
}