2

I have following code in my SwiftUI project

@FetchRequest private var step: FetchedResults<Steps>
private var processID: UUID
private var stepID: UUID?

init(procID: UUID, stepID: UUID?) {
    if stepID != nil {
        let predicate = NSPredicate(format: "id == %@", stepID! as CVarArg)
        _step = FetchRequest<Steps>(sortDescriptors: [], predicate: predicate)
    }
    processID = procID
}

and I'm wondering if I can somehow return empty step FetchRequest from init() in case that stepID passed is nil. It's not compiled currently because step var is not initialized. I was trying to make optional but compiler doesn't like it.

Dawy
  • 770
  • 6
  • 23

2 Answers2

5

You can always return a FALSEPREDICATE if stepID is nil. This will give you an empty @FetchRequest, but a non-optional predicate argument.

init(procID: UUID, stepID: UUID?) {
    let predicate: NSPredicate
    if let stepID = stepID {
       predicate = NSPredicate(format: "id == %@", stepID as CVarArg)
    } else {
       // This will return a predicate that matches nothing, so your fetch
       // will be empty. 
       predicate = NSPredicate(format: "FALSEPREDICATE")
    }
        _step = FetchRequest<Steps>(sortDescriptors: [], predicate: predicate)

    processID = procID
}
Yrb
  • 8,103
  • 2
  • 14
  • 44
0

The predicate passed to FetchRequest's init can be nil so you can do:

private var fetchRequest: FetchRequest<Steps>
private var steps: FetchedResults<Steps> {
    fetchRequest.wrappedValue
}

init(stepID: UUID?) {
    let predicate: NSPredicate?
    if let stepID = stepID {
        predicate = NSPredicate(format: "id == %@", stepID)
    }
    else {
        predicate = nil
    }
    fetchRequest = FetchRequest(sortDescriptors: [], predicate: predicate)
}
malhal
  • 26,330
  • 7
  • 115
  • 133