Is there any way I can catch assertions in Swift? Is there any way I can catch assertions in Swift? swift swift

Is there any way I can catch assertions in Swift?


As you mentioned, assertions will crash your app in debug or production. They aren't designed to function like Java/C# exceptions. Their only real purpose is:

Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution. ... in situations where invalid conditions are possible, an assertion is an effective way to ensure that such conditions are highlighted and noticed during development, before your app is published.

Since you can use Cocoa classes in Swift, you're still able to use NSException for exceptional things that your code can handle.


You can add try-catch support for Swift by following the instructions in this article: https://medium.com/@_willfalcon/adding-try-catch-to-swift-71ab27bcb5b8

Basically, it's a wrapper around Obj-C try-catch


From Apple books, The Swift Programming Language it's seems erros should be handle using enum.

Here is an example from the book.

enum ServerResponse {    case Result(String, String)    case Error(String)}let success = ServerResponse.Result("6:00 am", "8:09 pm")let failure = ServerResponse.Error("Out of cheese.")switch success {case let .Result(sunrise, sunset):    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."case let .Error(error):    let serverResponse = "Failure...  \(error)"}

From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l

For unexpected erros you should use NSException as point out by lfalin