How to create @Query based on input

Overview

  • I have a view B contains @Query for cars, now this @Query predicate depends on an input which is passed from view A.

Current approach

  • I am creating @Query in the init of view B by using _cars.

Questions

  1. Now how can I compose @Query based on input from view A?
  2. Is my approach correct? In my approach Query will be created every time init gets called
  3. Or is there a better approach?
Answered by DTS Engineer in 893274022

Yeah, your approach is the way to go (and you are right that a query will be created "every time init gets called"). The following code example shows how to create a query with a predicate and a sort key path in the view's init:

struct SentenceListView: View {
    @Query() private var sentences: [Sentence]
    
    init(searchText: String) {
        let predicate = ... // Create a predicate with `searchText`
        _sentences = Query(filter: predicate, sort: \Sentence.text)
    }
    ...
}

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Yeah, your approach is the way to go (and you are right that a query will be created "every time init gets called"). The following code example shows how to create a query with a predicate and a sort key path in the view's init:

struct SentenceListView: View {
    @Query() private var sentences: [Sentence]
    
    init(searchText: String) {
        let predicate = ... // Create a predicate with `searchText`
        _sentences = Query(filter: predicate, sort: \Sentence.text)
    }
    ...
}

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

How to create @Query based on input
 
 
Q