Che*_*rK2 10 try-catch throw ios swiftui
我在某些视图中有一个按钮,它调用 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")
}
Run Code Online (Sandbox Code Playgroud)
try-catch 块产生以下错误:
Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'
Run Code Online (Sandbox Code Playgroud)
这是 viewModel 中的 createInstance 函数,taskModel 函数以同样的方式处理错误。
func createIntance(name: String) throws {
do {
try taskModel.createInstance(name: name)
} catch {
throw DatabaseError.CanNotBeScheduled
}
}
Run Code Online (Sandbox Code Playgroud)
如何正确捕获 SwiftUI 中的错误?
警报显示正在使用.alert修饰符,如下所示
@State private var isError = false
...
Button(action: {
do {
try self.taskViewModel.createInstance(name: self.name)
} catch DatabaseError.CanNotBeScheduled {
// do something else specific here
self.isError = true
} catch {
self.isError = true
}
}) {
Text("Save")
}
.alert(isPresented: $isError) {
Alert(title: Text("Can't be scheduled"),
message: Text("Try changing the name"),
dismissButton: .default(Text("OK")))
}
Run Code Online (Sandbox Code Playgroud)