英文:
Error "Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure" in Swift
问题
我尝试在我的Swift应用中添加一个实时活动。但是当我尝试运行应用程序时,出现错误消息"传递给不接受闭包的参数的尾随闭包类型为'NSManagedObjectContext'"。我的应用程序使用Core Data来保存应用程序的数据。
class HabitManager: ObservableObject {
private var activity: Activity<HabitsWidgetAttributes>? = nil
func startHabit(name: String, symbol: String, currentTask: String) {
let attributes = HabitsWidgetAttributes(name: name, symbol: symbol)
let state = HabitsWidgetAttributes.ContentState(currentTask: currentTask)
activity = try? Activity<HabitsWidgetAttributes>.request(attributes: attributes, contentState: state)
}
func updateActivity(nextTask: String) {
let state = HabitsWidgetAttributes.ContentState(currentTask: nextTask)
Task { // 产生错误的行
await activity?.update(using: state)
}
}
func stopActivity() {
let state = HabitsWidgetAttributes.ContentState(currentTask: "Finished")
Task { // 产生错误的行
await activity?.end(using: state, dismissalPolicy: .immediate)
}
}
}
英文:
I try to add a live activity to my app, in Swift. But when I try to run the app, the error message "Trailing closure passed to parameter of type 'NSManagedObjectContext' that does not accept a closure" appear. My app uses Core Data to save the data of my app.
class HabitManager: ObservableObject {
private var activity: Activity<HabitsWidgetAttributes>? = nil
func startHabit(name: String, symbol: String, currentTask: String) {
let attributes = HabitsWidgetAttributes(name: name, symbol: symbol)
let state = HabitsWidgetAttributes.ContentState(currentTask: currentTask)
activity = try? Activity<HabitsWidgetAttributes>.request(attributes: attributes, contentState: state)
}
func updateActivity(nextTask: String) {
let state = HabitsWidgetAttributes.ContentState(currentTask: nextTask)
Task { // Line where the error is generated
await activity?.update(using: state)
}
}
func stopActivity() {
let state = HabitsWidgetAttributes.ContentState(currentTask: "Finished")
Task { // Line where the error is generated
await activity?.end(using: state, dismissalPolicy: .immediate)
}
}
}
答案1
得分: 5
如果您创建了一个名为Task的CoreData实体,那么编译器将尝试使用它,而不是Swift的Task
结构体。
您可以将您的CoreData实体重命名为其他名称(我建议这样做),或者您可以通过在模块前缀之前调用一个异步任务来调用它,就像这样:
Swift.Task {
// 进行操作
}
由于您必须在所有地方都这样做,我强烈建议重命名您的实体。
英文:
If you create a CoreData entity called Task, then the compiler will try to use that instead of the Swift Task
struct.
You can either rename your CoreData entity to something else (which I'd recommend), or you can call an async task by prefixing it with the module, in this case it would look like this:
Swift.Task {
// do stuff
}
Since you'd have to do that everywhere, I would strongly recommend renaming your entity instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论