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?
Overview. Attributed strings are character strings that have attributes for individual characters or ranges of characters. Attributes provide traits like visual styles for display, accessibility for guided access, and hyperlink data for linking between data sources.
The joined() method returns a new string by concatenating all the elements in an array, separated by a specified separator.
Swift 5:
import Foundation
extension Sequence where Iterator.Element == NSAttributedString {
func joined(with separator: NSAttributedString) -> NSAttributedString {
return self.reduce(NSMutableAttributedString()) {
(r, e) in
if r.length > 0 {
r.append(separator)
}
r.append(e)
return r
}
}
func joined(with separator: String = "") -> NSAttributedString {
return self.joined(with: NSAttributedString(string: separator))
}
}
Swift 4:
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))
}
}
Took this solution from SwifterSwift, it's similar to the other ones:
public extension Array where Element: NSAttributedString {
func joined(separator: NSAttributedString) -> NSAttributedString {
guard let firstElement = first else { return NSMutableAttributedString(string: "") }
return dropFirst().reduce(into: NSMutableAttributedString(attributedString: firstElement)) { result, element in
result.append(separator)
result.append(element)
}
}
func joined(separator: String) -> NSAttributedString {
guard let firstElement = first else { return NSMutableAttributedString(string: "") }
let attributedStringSeparator = NSAttributedString(string: separator)
return dropFirst().reduce(into: NSMutableAttributedString(attributedString: firstElement)) { result, element in
result.append(attributedStringSeparator)
result.append(element)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With