Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way I can catch assertions in Swift?

It seems that Swift doesn't have C#/Java-like exceptions and uses assertions instead. However, the book says that in production environment, they instantly crash the app. Isn't there a way around it? What about unit tests, how can I test that a certain function asserts that it gets a correct input value?

like image 962
Max Yankov Avatar asked Jun 02 '14 21:06

Max Yankov


People also ask

How do you catch an assertion?

In order to catch the assertion error, we need to declare the assertion statement in the try block with the second expression being the message to be displayed and catch the assertion error in the catch block.

What does the assert () function do in Swift?

Swift lets you force an app crash using the assert() function. This takes two parameters: a condition to check, and a message to print if the assertion fails.

Can we handle assertion error?

In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.


2 Answers

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.

like image 92
lfalin Avatar answered Oct 13 '22 14:10

lfalin


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

like image 31
William Falcon Avatar answered Oct 13 '22 15:10

William Falcon