7

For fetching data, there's a fetchCount() available:

let descriptor = FetchDescriptor<Employee>(predicate: #Predicate { $0.salary > 100_000 })
let count = (try? modelContext.fetchCount(descriptor)) ?? 0

Is there a way to use something similar for the @Query property wrapper? This is the current alternative, but it might be loading more than it has to:

@Query(filter: #Predicate<Employee> { $0. salary > 100_000 }) var employees

inside the view:

if !employees.isEmpty {
    // show something
}
6
  • What do you mean with "it might be loading more than it has to"? Do you need the employees array or just the count? Commented Jan 26, 2024 at 9:06
  • Why not use the first code snippet in onAppear and assign the result to a @State property? Commented Jan 26, 2024 at 9:06
  • 1
    @Timmy I just want the count. The reason I said "might" is because afaik it's trying to be smart about what to load. If I only access the count, maybe it's already not loading everthing Commented Jan 26, 2024 at 9:10
  • 1
    @JoakimDanielson that wouldn't update the data if it changes, right? Commented Jan 26, 2024 at 9:11
  • 1
    No there isn’t, you can use a computed property so it refreshes when the view refreshes Commented Jan 26, 2024 at 9:18

1 Answer 1

0

If it's just about checking if any item exists that matches the filter, this is faster:

struct MyView: View {
    @Query(MyView.descriptor) var employees: [Employee]
    
    var body: some View {
        if !employees.isEmpty {
            // show something
        }
    }
    
    static var descriptor: FetchDescriptor<Employee> {
        var descriptor = FetchDescriptor<Employee>(
            predicate: #Predicate<Employee> { $0.salary > 100_000 }
        )
        descriptor.fetchLimit = 1 // <-- only fetch one
        return descriptor
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.