0

我的 SwiftUI 项目中有以下代码

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

我想知道如果传递的stepID为nil,我是否可以以某种方式从init()返回空步骤FetchRequest。当前未编译,因为 step var 未初始化。我试图使其成为可选,但编译器不喜欢它。

4

1 回答 1

1

你总是可以返回一个FALSEPREDICATEifstepID为 nil。这会给你一个空的@FetchRequest,但非可选的谓词参数。

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
}
于 2022-02-15T18:25:56.047 回答