gpt4 book ai didi

swiftui - 如何选择性地初始化@FetchRequest

转载 作者:行者123 更新时间:2023-12-02 18:18:57 27 4
gpt4 key购买 nike

我的 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
}

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

最佳答案

如果 stepID 为零,您始终可以返回 FALSEPREDICATE。这将为您提供一个空的@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
}

关于swiftui - 如何选择性地初始化@FetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71131365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com