Sort Document Names Naturally And Keep Ties Predictable

A document browser puts Report 10 before Report 2. You fix the name comparison, refresh the list, and two documents with the same title swap places. Then someone chooses descending order and the folders sink to the bottom.

That sort button has acquired a surprisingly large job description.

We can give it one small, explicit policy: folders first, names in the selected direction, and persistent IDs to settle ties. Foundation already has the pieces; we just need to decide which rule wins.

Pick the comparison that matches the screen

Swift’s ordinary string ordering is useful, but a filename browser usually needs numeric segments compared as numbers: Report 2 before Report 10. Foundation’s localized standard comparator provides a localized, numeric comparison in the current locale.

The Stack Overflow question about sorting strings containing numbers already has an answer using that comparator. The multiple-criteria sorting question has answers too. The missing piece for our screen is the product policy that combines those techniques and remains predictable when input arrives in another order.

John Sundell’s article on sorting collections explores composing criteria, including custom descriptor helpers. For this example, Foundation’s KeyPathComparator supplies that composition without a helper framework or an NSObject model.

The comparator APIs used here require iOS 15 or macOS 12. The examples were checked with Xcode 27.2 and Swift 6.4.2; explicit nonisolated declarations keep these values and functions outside a project’s default MainActor isolation. Put the following Swift blocks in the same file, in order.

Make the priorities visible

Our entries are value snapshots, not live file-system objects. The ID comes from the stored record and stays the same across refreshes.

import Foundation

nonisolated struct DocumentEntry: Identifiable, Equatable, Sendable {
    let id: Int64
    let name: String
    let isFolder: Bool

    var folderRank: Int { isFolder ? 0 : 1 }
}

nonisolated func documentOrder(
    nameOrder: SortOrder = .forward
) -> [KeyPathComparator<DocumentEntry>] {
    [
        KeyPathComparator(\.folderRank),
        KeyPathComparator(
            \.name,
            comparator: String.Comparator.localizedStandard,
            order: nameOrder
        ),
        KeyPathComparator(\.id)
    ]
}

The comparator list is evaluated in priority order. Only an .orderedSame result lets the next criterion decide. Using the comparison result matters: equality for sorting means equal under that comparator, which need not be the same question as String ==.

#RuleReversed for descending names?
1Folder rank, ascendingNo
2Localized standard name comparisonYes
3Persistent ID, ascendingNo

Keep IDs unique across the entries being sorted. If folders and documents use separate numeric ID spaces, give the combined list a genuinely unique identifier before using this example. An array offset, hashValue, or a newly generated UUID on every refresh cannot provide persistent identity.

Reverse the names, not the entire result

Here’s a complete call site with two folders and two different records named Report 2:

nonisolated func documentSortingExample() -> (
    ascending: [DocumentEntry], descending: [DocumentEntry]
) {
    let entries = [
        DocumentEntry(id: 40, name: "Report 10", isFolder: false),
        DocumentEntry(id: 30, name: "Report 2", isFolder: false),
        DocumentEntry(id: 5, name: "Folder 10", isFolder: true),
        DocumentEntry(id: 20, name: "Report 2", isFolder: false),
        DocumentEntry(id: 4, name: "Folder 2", isFolder: true)
    ]

    let ascending = entries.sorted(using: documentOrder())
    let descending = entries.sorted(
        using: documentOrder(nameOrder: .reverse)
    )

    assert(ascending.map(\.id) == [4, 5, 20, 30, 40])
    assert(descending.map(\.id) == [5, 4, 40, 20, 30])
    return (ascending, descending)
}

Both results keep folders ahead of documents. Descending names place Report 10 before Report 2, while the two Report 2 records still appear as IDs 20 then 30.

Calling reversed() on the ascending result would also reverse the folder grouping and the ID tie-breaker. Likewise, setting every comparator’s order to .reverse changes all three policies. Change only the name comparator when that is what the control promises.

Stable sorting doesn’t settle unspecified ties

Swift’s sorting is stable: elements that compare equally retain their relative input order. SE-0372 made that guarantee explicit; it did not introduce a new sorting algorithm.

That is useful when preserving input order is your intention. But if one response contains equal-name records as [30, 20] and the next contains [20, 30], a stable name-only sort preserves two different orders. It cannot recover a preference the comparator never expressed.

The final ID comparison settles that ambiguity. For the same records, names, folder flags, and comparison behavior, the output no longer depends on arrival order. Rename a document or change its folder flag and it can move; that’s a real change to the sorting inputs.

This is related to the persistent tie-breaker in our stable SwiftData cursor article, but the boundary is different: here we’re arranging an already loaded collection for display.

Keep display ordering out of your wire protocol

Localized ordering is a user-facing choice, not a canonical order shared by every device. Apple explicitly warns that Finder-style comparison can vary by locale and OS release. Recreate the ordering and re-sort when adopting a changed locale. Don’t persist array positions as document identity or use this localized order as an undocumented server cursor contract.

Also avoid lowercasing every name or extracting integers yourself just to make the sort work. That creates another text policy to maintain. Natural filename order is not semantic-version ordering or a parser for signed decimal measurements; those domains need their own rules.

If two records look identical to a person, a deterministic ID tie-breaker still won’t explain which one to open. Show a useful subtitle such as the parent folder or modification date. Predictable placement and recognizable content solve different problems.

Test changed input, not just one tidy array

The standalone sample and checks contain these exact declarations and test every permutation of the five-entry fixture in both directions. They also demonstrate three mistakes: ordinary string sorting puts Report 10 first, removing the ID tie-breaker makes equal names depend on input order, and reversing the finished array puts documents before folders.

Additional checks cover empty and single-entry collections, Unicode names, and comparison consistency. The same behavior checks passed on macOS 27.2.1 and an iOS 27.2 simulator, with ordinary and MainActor default isolation; the code also compiles for the stated minimum deployment targets. That is runtime evidence for those systems, not a guarantee that every locale or OS version produces identical collation.

The result is a small ordering policy you can read from top to bottom—and a descending button that only reverses what it says it reverses.