如何在SwiftData中为@Query指定自定义排序顺序?

huangapple go评论87阅读模式
英文:

How do I specify a custom sort order for @Query in SwiftData?

问题

当我指定基于String类型的排序顺序时,SwiftData会对列表进行区分大小写的排序:

如果我的模型如下所示:

import Foundation
import SwiftData

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

然后在我的视图顶部,我这样做:

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

如果我的数据包含以下内容:["a", "B", "C"],则项目将以以下顺序返回:["B", "C", "a"]。

我该如何让SwiftData在排序时不区分大小写?

英文:

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?

答案1

得分: 1

以下是翻译好的部分:

最简单的解决方案是,如果您可以使用已存在的String标准比较之一,它们在String.StandardComparator中定义。

对我来说,localizedlocalizedStandard 都根据您的要求有效。

@Query(sort: [SortDescriptor(\.name, comparator: .localized)]) private var items: [Item]
英文:

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]

huangapple
  • 本文由 发表于 2023年7月23日 15:05:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定