Search code examples
swiftuiinitfetchrequest

How to initialize @FetchRequest optionally


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.


Solution

  • 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
    }