Thursday, January 18, 2018

How should one handle errors in Swift?

The method for handling errors in Swift differ a bit from Objective-C. In Swift, it's possible to declare that a function throws an error. It is, therefore, the caller's responsibility to handle the error or propagate it. This is similar to how Java handles the situation.

You simply declare that a function can throw an error by appending the throws keyword to the function name. Any function that calls such a method must call it from a try block.

func canThrowErrors() throws -> String

//How to call a method that throws an error
try canThrowErrors()

//Or specify it as an optional
let maybe = try? canThrowErrors()