Imagine you had to join together attributed strings with a separator in between them. Which of the following methods would you use?
An extension on SequenceType with a function that takes in a separator. Can't use any optionals in the array.
extension SequenceType where Generator.Element: NSAttributedString {
func join(withSeparator separator: NSAttributedString) -> NSAttributedString {
var shouldAddSeparator = true
return self.reduce(NSMutableAttributedString()) {(element, sequence) in
if shouldAddSeparator {
shouldAddSeparator = false
}
else {
element.appendAttributedString(separator)
}
element.appendAttributedString(sequence)
return element
}
}
}
A private function that takes in an array of optional NSAttributedString and a separator.
private func join(attributedStrings strings: [NSAttributedString?], withSeparator separator: NSAttributedString) -> NSAttributedString? {
let unwrappedStrings = strings.flatMap{$0} as [NSAttributedString]
guard unwrappedStrings.count == strings.count else { return nil }
let finalString = NSMutableAttributedString()
for (index, string) in unwrappedStrings.enumerate() {
if index == 0 {
finalString.appendAttributedString(string)
}
else {
finalString.appendAttributedString(separator)
finalString.appendAttributedString(string)
}
}
return finalString
}
Extension on _ArrayType that can take in an array of options NSAttributedString
extension _ArrayType where Generator.Element == NSAttributedString? {
private func join(withSeparator separator: NSAttributedString) -> NSAttributedString? {
let unwrappedStrings = flatMap{$0} as [NSAttributedString]
var shouldAddSeparator = false
return unwrappedStrings.reduce(NSMutableAttributedString(), combine: { (string, element) in
if shouldAddSeparator {
string.appendAttributedString(separator)
}
else {
shouldAddSeparator = true
}
string.appendAttributedString(element)
return string
})
}
}