@@ -2,23 +2,48 @@ import Foundation
22
33public extension String {
44 /// The line ending of the string.
5+ ///
6+ /// We are pretty safe to just check the last character here, in most case, a line ending
7+ /// will be in the end of the string.
8+ ///
9+ /// For other situations, we can assume that they are "\n".
510 var lineEnding : Character ? {
6- last ( where: \. isNewline)
11+ if let last, last. isNewline { return last }
12+ return " \n "
13+ }
14+
15+ func splitByNewLine(
16+ omittingEmptySubsequences: Bool = true ,
17+ fast: Bool = true
18+ ) -> [ Substring ] {
19+ if fast {
20+ let lineEndingInText = lineEnding ?? " \n "
21+ return split (
22+ separator: lineEndingInText,
23+ omittingEmptySubsequences: omittingEmptySubsequences
24+ )
25+ }
26+ return split (
27+ omittingEmptySubsequences: omittingEmptySubsequences,
28+ whereSeparator: \. isNewline
29+ )
730 }
831
932 /// Break a string into lines.
1033 func breakLines(
1134 proposedLineEnding: String ? = nil ,
1235 appendLineBreakToLastLine: Bool = false
1336 ) -> [ String ] {
14- let lineEnding = proposedLineEnding ?? String ( lineEnding ?? " \n " )
15- let lines = split ( omittingEmptySubsequences: false , whereSeparator: \. isNewline)
37+ let lineEndingInText = lineEnding ?? " \n "
38+ let lineEnding = proposedLineEnding ?? String ( lineEndingInText)
39+ // Split on character for better performance.
40+ let lines = split ( separator: lineEndingInText, omittingEmptySubsequences: false )
1641 var all = [ String] ( )
1742 for (index, line) in lines. enumerated ( ) {
1843 if !appendLineBreakToLastLine, index == lines. endIndex - 1 {
1944 all. append ( String ( line) )
2045 } else {
21- all. append ( String ( line) + String ( lineEnding) )
46+ all. append ( String ( line) + lineEnding)
2247 }
2348 }
2449 return all
0 commit comments