[SwiftData] How to get the first 7 elements by using @Query?

Maybe I didn't find the relevant instructions.

In my code, I only want to get the first 7 elements.

At present, my code is as follows:

@Query(sort:\Record.date, order: .reverse) private var records:[Record]

But I wonder if once the number of records is large, will it affect the efficiency?

In View, it is enough for me to count the first 7 elements in records. What should I do?

Answered by joadan in 813354022

If you create the query property using a FetchDescriptor then you can set a limit for the number of rows being fetched. The drawback of this solution is that it's not a one liner so you need to do it in the init

@Query private var records:[Record]

init() {
    var fetchDescriptor = FetchDescriptor<Record>(sortBy: [SortDescriptor(\Record.date, order: .reverse)])
    fetchDescriptor.fetchLimit = 7

    _categories = Query(fetchDescriptor)
}

If you for some reason don't want to do it in the init you could declare the fetch descriptor as a static variable and then pass it to the @Query declaration

Accepted Answer

If you create the query property using a FetchDescriptor then you can set a limit for the number of rows being fetched. The drawback of this solution is that it's not a one liner so you need to do it in the init

@Query private var records:[Record]

init() {
    var fetchDescriptor = FetchDescriptor<Record>(sortBy: [SortDescriptor(\Record.date, order: .reverse)])
    fetchDescriptor.fetchLimit = 7

    _categories = Query(fetchDescriptor)
}

If you for some reason don't want to do it in the init you could declare the fetch descriptor as a static variable and then pass it to the @Query declaration

[SwiftData] How to get the first 7 elements by using @Query?
 
 
Q