Start learning free

LESSON 22 OF 71 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in Swift: Descending Order with sorted(by:)

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

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

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Use sorted(by: >) to get a new array in descending order without mutating the input.

The full solution:
class Solution {
    func sortLines(_ lines: [String]) -> String {
        let sortedLines = lines.sorted(by: >)
        return sortedLines.joined(separator: "\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in Swift, explained

    Problem overview

    The second version of the sort tool bakes in the -r flag. sortLines(_ lines: [String]) -> String returns the lines in descending order by character code, joined with "\n". It is the exact reverse of the previous version's order: lowercase letters now come before uppercase ones. Duplicates are kept, and an empty list gives "".

    For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple".

    Approach: tell sorted(by:) which element goes first

    The previous version called sort(), which uses the default ascending order. To change the direction, give the sort an ordering rule. Swift's sorted(by:) takes a function that receives two elements and answers one question: should the first one come before the second? For ascending order the answer is a < b. For descending order it is a > b.

    Operators are functions in Swift, so you can pass > itself as that rule. There is no need to write a closure like { $0 > $1 }, although that works the same way.

    Step by step

    1. Create sortedLines with let, from lines.sorted(by: >). sorted(by:) returns a new array and leaves lines alone, so no var copy and no in-place call are needed. The > makes the larger string go first.
    2. Return sortedLines.joined(separator: "\n"). The separator goes between lines only, so there is no trailing newline.

    The solution in Swift

        func sortLines(_ lines: [String]) -> String {
            let sortedLines = lines.sorted(by: >)
            return sortedLines.joined(separator: "\n")
        }
    

    Details that matter:

    • sorted and sort come in pairs. sorted(by:) returns a new array; sort(by:) changes a var in place. Both take the same ordering rule. This version uses the returning form, which is why sortedLines can be a let.
    • Passing an operator. by: > works because the compiler picks the > that takes two String values. The array's element type decides that, so the same code sorts an array of integers in descending order too.
    • The rule must be strict. > says "strictly greater", which is what a sorting rule needs. Writing >= breaks that requirement and can lead to unpredictable results.
    • Character-code order. Strings compare character by character. Uppercase ASCII letters have smaller codes than lowercase ones, so in descending order "apple" comes before "Zebra".

    Complexity

    Time: O(n log n) comparisons for n lines, each costing up to the length of the shorter line. Space: O(n), for the new sorted array and the joined result.

    Edge cases and common mistakes

    • Sorting first, then reversing. Calling sorted() and then reversing the array gives the same order for strings, but it takes an extra step. sorted(by: >) says what you mean in one call.
    • Duplicates. ["b", "a", "b"] returns "b\nb\na". Every copy stays.
    • The empty line goes last. It is the smallest string, so in descending order ["b", "", "a"] returns "b\na\n". The output ends with a newline because the last line is empty. That is the correct result, not a trailing separator.
    • Lowercase before uppercase. ["apple", "Zebra"] returns "apple\nZebra".
    • Empty input. An empty array stays empty after sorting, and joining it gives "".
    • Calling sort(by: >) on a let value. That is a compile error, because sorting in place needs a var. Use sorted(by:) when the result goes into a let.

    Testing

    • ["banana", "apple", "cherry"] gives "cherry\nbanana\napple".
    • ["apple", "Zebra"] gives "apple\nZebra".
    • ["b", "", "a"] gives "b\na\n".
    • ["b", "a", "b"] gives "b\nb\na".
    • [] 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