In this tutorial you will learn all about error handling in Swift. You'll learn about all the new features added in Swift 2.0 and discover how to use them.
Great tutorial on error handling! The witch theme was a really nice touch that kept the tutorial fun and interesting. I really enjoyed your writing style and use of playgrounds. Thank you.
I think this modified function will do what youâre looking for:
func retrieveFailureDetails(from error: ChangoSpellError) -> String {
var details = ""
switch error {
case .hatMissingOrNotMagical:
details = "Did you forget your hat, or does it need its batteries charged?"
case .familiarAlreadyAToad:
details = "Why are you trying to change a Toad into a Toad?"
default: break
}
return details
}
It stores the information into var details for each of the cases, and returns it (rather than printing it to the console).
@gemmakbarlow Thank you for your reply. My question was how can I access value stored in the variable reason Thank you very much.
enum ChangoSpellError: Error {
case hatMissingOrNotMagical
case noFamiliar
case familiarAlreadyAToad case spellFailed(reason: String)
case spellNotKnownToWitch
}
No problem! Right, I understand what youâre asking more clearly now - good question.
You can extract an associated value using either let or var alongside the case statement - e.g.
case .spellFailed(let reason):
// Do something with âreasonâ here
or
case .spellFailed(var reason):
// Do something with âreasonâ here
Normal swift rules apply when deciding to use let or var - when in doubt, start with let.
Additionally, you could have used someReason instead of reason here - it doesnât need to match the name given when defining the enum (though Iâd recommend that to make your code nice and clear).
The official Apple documentation regarding this can be found here - The Swift Programming Language: Redirect - but itâs buried a bit, so try searching for âextractâ as a keyword.
Hello Gemma! Do you know how can i make non throwable async functions into synchronous?
I can do thant above:
func lastPlacemarks() throws -> [CLPlacemark]? {
var pError: Error?
var pPlacemarks: [CLPlacemark]?
guard let location = lastLocation else {
return nil
}
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if error != nil {
pError = error
}
pPlacemarks = placemarks
})
if (pError != nil) {
throw pError!
}
return pPlacemarks
}
âlastLocationâ is a filled variable in my current class, but the reverseGeocodeLocation function wasnât called because itâs an async function, itâs running detached of current thread, this funcition returns pPlacemarks as a nil value, in all time.