2

I have a utiltiy function that saves data to CoreData.

func saveData(content: String) throws -> Void {
    // saves a model to CoreData
}

I want to fire this function when a Button is tapped by a user. Something like

Button(action: saveData)

But when I attempt this I get an error Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'.

Is it possible to do what I am imagining or is there some other best practice I should be doing?

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Paul
  • 1,101
  • 1
  • 11
  • 20
  • 1
    https://stackoverflow.com/questions/63621431/catching-errors-in-swiftui – Mike Taverne Oct 22 '22 at 01:32
  • Oh nice. So it seems like I need to toggle some Boolean value to catch it outside then do something else, is that right? – Paul Oct 22 '22 at 01:35
  • 1
    That was the solution presented in that post. Mostly I was just trying to suggest how to call the throwing function. But yeah, I guess you have to figure out what to do if the save fails :) – Mike Taverne Oct 22 '22 at 01:36
  • Awesome, thank you @MikeTaverne looks promising. I'll try it out – Paul Oct 22 '22 at 01:39
  • For posterity, you cannot throw directly from within the `Button` view or any view but instead you have to catch and toggle a boolean than fire off an `.alert` as a view modifier. https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l – Paul Oct 22 '22 at 02:03
  • if you `throw` you need to use `do try catch` to handle the error – lorem ipsum Oct 22 '22 at 03:07

1 Answers1

1
@State private var showError = false

Button(action: {
do {
try saveData()
} catch {
showError = true
}
}, label: { 
...
})

Then show the error with the .alert modifier

sxcrbu
  • 11
  • 1