Introduce 'splitByNewline' string extension

This commit is contained in:
Danny Moesch 2020-01-18 22:30:38 +01:00 committed by Mingshen Sun
parent 2ffc9ba568
commit 56b2205376
3 changed files with 9 additions and 9 deletions

View file

@ -29,14 +29,12 @@ class UICodeHighlightingLabel: UILocalizedLabel {
/// - Parameter text: Multiline string block /// - Parameter text: Multiline string block
/// - Returns: Same multiline string block with code sections formatted /// - Returns: Same multiline string block with code sections formatted
private func formatCode(in text: String) -> NSMutableAttributedString { private func formatCode(in text: String) -> NSMutableAttributedString {
let formattedText = text let formattedText = text.splitByNewline()
.split(omittingEmptySubsequences: false) { .map { line -> NSAttributedString in
$0 == "\n" || $0 == "\r\n"
}.map { line -> NSAttributedString in
if line.starts(with: " ") { if line.starts(with: " ") {
return NSAttributedString(string: String(line), attributes: UICodeHighlightingLabel.CODE_ATTRIBUTES) return NSAttributedString(string: line, attributes: UICodeHighlightingLabel.CODE_ATTRIBUTES)
} }
return NSAttributedString(string: String(line)) return NSAttributedString(string: line)
}.reduce(into: NSMutableAttributedString(string: "")) { }.reduce(into: NSMutableAttributedString(string: "")) {
$0.append($1) $0.append($1)
$0.append(UICodeHighlightingLabel.ATTRIBUTED_NEWLINE) $0.append(UICodeHighlightingLabel.ATTRIBUTED_NEWLINE)

View file

@ -17,6 +17,10 @@ extension String {
allowed.insert(charactersIn: unreserved) allowed.insert(charactersIn: unreserved)
return addingPercentEncoding(withAllowedCharacters: allowed) return addingPercentEncoding(withAllowedCharacters: allowed)
} }
public func splitByNewline() -> [String] {
return split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r\n" }.map(String.init)
}
} }
extension String { extension String {

View file

@ -16,9 +16,7 @@ class Parser {
private(set) lazy var additionFields = getAdditionFields() private(set) lazy var additionFields = getAdditionFields()
init(plainText: String) { init(plainText: String) {
let splittedPlainText = plainText let splittedPlainText = plainText.splitByNewline()
.split(omittingEmptySubsequences: false) { $0 == "\n" || $0 == "\r\n" }
.map(String.init)
firstLine = splittedPlainText.first! firstLine = splittedPlainText.first!
additionsSection = splittedPlainText[1...].joined(separator: "\n") additionsSection = splittedPlainText[1...].joined(separator: "\n")