1

I am trying to use SwiftData for an application I was using CoreData for. When I specify a sort order based on a String type, it gives me a list sorted with case-sensitivity:

If my model looks like:

import SwiftData

@Model
final class Item {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

Then in my view at the top, I do:

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \.name) private var items: [Item]

If my data has the following in it: ["a", "B", "C"], Items will come back in the order ["B", "C", "a"].

How do I get SwiftData to sort without case-sensitivity?

Syd Polk
  • 73
  • 1
  • 5

1 Answers1

1

The easiest solution here is if you can use one of the standard comparisons that exists for String, they are defined in String.StandardComparator

For me localized and localizedStandard both worked according to your requirements.

@Query(sort: [SortDescriptor(\.name, comparator: .localized)]) private var items: [Item]
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • Thanks! That worked like a champ. I found the docs for String.StandardComparitor confusing. Having this example was really great. – Syd Polk Jul 23 '23 at 13:55