Skip to main content

How to get natural string sorting for SwiftData queries

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to get natural string sorting for SwiftData queries 관련

SwiftData by Example

Back to Home

How to get natural string sorting for SwiftData queries | SwiftData by Example

How to get natural string sorting for SwiftData queries

Updated for Xcode 15

If you sort strings using the default ordering, you'll get sorting like this: User 1, User 10, User 100, User 11, User 2, User 3, User 4, and so on – it will sort the numbers based on their string contents, rather than their numerical values.

A smarter, more natural option is to use Finder-style sorting, which correctly sorts strings based on any text prefix ("User"), followed by any numerical values. So, we'd get User 1, User 2, User 3, etc, up to User 9, then User 10, User 11, and so on.

To do this with SwiftData, create a SortDescriptor using the .localizedStandard comparator. For example, if you were using the @Query macro you'd write something like this:

@Query(sort: [SortDescriptor(\User.name, comparator: .localizedStandard)]) var users: [User]

It's such a small change, but makes for much more user-friendly sorting!


이찬희 (MarkiiimarK)
Never Stop Learning.