-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathString+LineEnding.swift
More file actions
52 lines (48 loc) · 1.61 KB
/
String+LineEnding.swift
File metadata and controls
52 lines (48 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import Foundation
public extension String {
/// The line ending of the string.
///
/// We are pretty safe to just check the last character here, in most case, a line ending
/// will be in the end of the string.
///
/// For other situations, we can assume that they are "\n".
var lineEnding: Character {
if let last, last.isNewline { return last }
return "\n"
}
func splitByNewLine(
omittingEmptySubsequences: Bool = true,
fast: Bool = true
) -> [Substring] {
if fast {
let lineEndingInText = lineEnding
return split(
separator: lineEndingInText,
omittingEmptySubsequences: omittingEmptySubsequences
)
}
return split(
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: \.isNewline
)
}
/// Break a string into lines.
func breakLines(
proposedLineEnding: String? = nil,
appendLineBreakToLastLine: Bool = false
) -> [String] {
let lineEndingInText = lineEnding
let lineEnding = proposedLineEnding ?? String(lineEndingInText)
// Split on character for better performance.
let lines = split(separator: lineEndingInText, omittingEmptySubsequences: false)
var all = [String]()
for (index, line) in lines.enumerated() {
if !appendLineBreakToLastLine, index == lines.endIndex - 1 {
all.append(String(line))
} else {
all.append(String(line) + lineEnding)
}
}
return all
}
}