Problem overview
The third version of the sort tool adds the -n flag. Each input line is the text of a 32-bit integer: an optional leading -, no +, and leading zeros such as "007" allowed. sortLines(_ lines: [String]) -> String sorts them by numeric value, ascending, and returns the original strings joined with "\n".
Lines with the same value keep their original relative order. For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". Sorted as text, "100" would come before "20", because the character "1" is smaller than "2".
Approach: compare the numbers, keep the text
The array holds strings, and the answer must contain those same strings, so the lines can't be converted once and thrown away. Instead, keep the strings in the array and teach the sort to compare them by value. sort accepts a closure that receives two elements and returns true when the first belongs before the second. Inside it, convert both strings to integers and compare those.
The conversion is Int(text). Swift's integer initializer from a string returns an optional, because the text may not be a number. The lesson guarantees valid integers, so the closure force-unwraps with !.
Step by step
- Copy
linesinto avarnamedsortedLines. Arrays are value types, so the caller's array is not changed by sorting the copy. - Sort in place with a closure.
$0and$1are the two lines being compared, and the closure returnsInt($0)! < Int($1)!. - Return
sortedLines.joined(separator: "\n"). The strings come out in their original spelling, so"007"stays"007".
The solution in Swift
func sortLines(_ lines: [String]) -> String {
var sortedLines = lines
sortedLines.sort { Int($0)! < Int($1)! }
return sortedLines.joined(separator: "\n")
}
Details that matter:
- Trailing closure syntax.
sortedLines.sort { ... }passes the closure after the call, without parentheses. It is the same assort(by: { ... }). - Shorthand arguments.
$0and$1are the closure's first and second parameters. A closure with a single expression returns that expression's value without writingreturn. Int(...)returns an optional.Int("007")isOptional(7),Int("-12")isOptional(-12), andInt("abc")isnil. The!turns the optional into a plainInt, and it stops the program if the value isnil. Since every line is valid here, it never fires.- No overflow worry.
Intis 64 bits in Swift, so 32-bit values fit with room to spare. The input["2147483647", "-2147483648", "0"]sorts to"-2147483648\n0\n2147483647". - Stability. Equal numbers must keep their input order. Swift's standard library does not promise a stable
sortin its documentation, but the current implementation is stable, and the lesson relies on that. With["007", "7", "06"], the 6 comes first, then"007"and"7"in the order they came in:"06\n007\n7".
Complexity
Time: O(n log n) comparisons, and each comparison parses two short strings, which costs time proportional to their length. Because every comparison re-parses its two lines, the parsing is repeated about log n times per line. Space: O(n) for the copy and the output.
Edge cases and common mistakes
- Text order instead of numeric order. Plain
sort()would put"100"before"20". The closure is the whole point of this version. - Negative numbers.
["-5", "3", "-12", "0"]gives"-12\n-5\n0\n3". Comparing parsed integers handles the sign; comparing text would not. - Leading zeros.
"007"and"7"are equal numerically, so they keep their input order:["7", "007", "7"]gives"7\n007\n7". - Returning the converted numbers. The output must show the original lines, so
"007"can't turn into"7". That is why only the comparison converts. - Empty list. Nothing to sort, and the result is
"".
Testing
["100", "20", "3", "10"]gives"3\n10\n20\n100".["-5", "3", "-12", "0"]gives"-12\n-5\n0\n3".["007", "7", "06"]gives"06\n007\n7".["7", "007", "7"]gives"7\n007\n7".["2147483647", "-2147483648", "0"]gives"-2147483648\n0\n2147483647".[]gives"".
