我在某个视图中有一个按钮,该按钮调用ViewModel中的函数,该函数可能会抛出错误。
Button(action: {
do {
try self.taskViewModel.createInstance(name: self.name)
} catch DatabaseError.CanNotBeScheduled {
Alert(title: Text("Can't be scheduled"), message: Text("Try changing the name"), dismissButton: .default(Text("OK")))
}
}) {
Text("Save")
}
try-catch 块会产生以下错误:
Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'
这是viewModel中的createInstance功能,taskModel函数以完全相同的方式处理错误。
func createIntance(name: String) throws {
do {
try taskModel.createInstance(name: name)
} catch {
throw DatabaseError.CanNotBeScheduled
}
}
如何在SwiftUI中正确捕获错误?