3

How do I do use @FetchRequest with a parameter passed to a struct?

struct TodoItemView: View {
    var todoList: TodoList
    @FetchRequest(
        entity: TodoItem.entity(),
        sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)],
        predicate: NSPredicate(format: "todoList == %@", todoList)
    ) var todoItems: FetchedResults<TodoItem>
    ...

I have todoList set up as a One relationship of TodoItem via TodoList.

It is giving me the error:

Cannot use instance member 'todoList' within property initializer; property initializers run before 'self' is available

How do I do a @FetchRequest with this relationship if I can't use it in the initializer? Also, should I be using todoList.objectID somewhere here instead?

kdion4891
  • 1,169
  • 12
  • 17

1 Answers1

10

Figured it out:

var todoList: TodoList
@FetchRequest var todoItems: FetchedResults<TodoItem>

init(todoList: TodoList) {
    self.todoList = todoList
    self._todoItems = FetchRequest(
        entity: TodoItem.entity(),
        sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)],
        predicate: NSPredicate(format: "todoList == %@", todoList)
    )
}

Thanks to similar answers here: SwiftUI View and @FetchRequest predicate with variable that can change

kdion4891
  • 1,169
  • 12
  • 17