英文:
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中定义。
对我来说,localized
和 localizedStandard
都根据您的要求有效。
@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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论