Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading