Start learning free

LESSON 23 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in Swift: Numeric Order with a Sort Closure

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

func sortLines(_ lines: [String]) -> String

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Sort with a closure that converts each operand to an Int via Int(...) and compares numerically. The strings themselves stay unchanged.

The full solution:
class Solution {
    func sortLines(_ lines: [String]) -> String {
        var sortedLines = lines
        sortedLines.sort { Int($0)! < Int($1)! }
        return sortedLines.joined(separator: "\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Swift, explained

    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

    1. Copy lines into a var named sortedLines. Arrays are value types, so the caller's array is not changed by sorting the copy.
    2. Sort in place with a closure. $0 and $1 are the two lines being compared, and the closure returns Int($0)! < Int($1)!.
    3. 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 as sort(by: { ... }).
    • Shorthand arguments. $0 and $1 are the closure's first and second parameters. A closure with a single expression returns that expression's value without writing return.
    • Int(...) returns an optional. Int("007") is Optional(7), Int("-12") is Optional(-12), and Int("abc") is nil. The ! turns the optional into a plain Int, and it stops the program if the value is nil. Since every line is valid here, it never fires.
    • No overflow worry. Int is 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 sort in 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 "".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free