Swift not well known api, assertionFailure() api saves your dev life

KD Knowledge Diet
2 min readMay 5, 2023

Have you ever heard of assertionFailure()? Working as an iOS Developer for four years, it’s a shame I finally found this api… This is enormously helpful when debugging your app.

assertionFailure() is a function in Swift that is used to stop the execution of a program.This function is a part of the Swift Standard Library and is used primarily for debugging purposes. In this article, we will explore what assertionFailure() is, how it works, and when to use it.

What is AssertionFailure()?

assertionFailure() is a function in Swift that is used to stop the execution of a program. When assertionFailure() is called, the program terminates immediately, indicating that an assertion has failed.

Here is an example:

var someValue: Int? 

guard let someValue = someValue else {
assertionFailure("some value should not be nil")
return
}

In this example, someValue is declared as an optional. Therefore, in order to access it safely, we need to unwrap it.

If someValue is nil, the program will stop immediately. It seems to be the same with fatalError() but there is a major difference between fatalError() and assertionFailure().

When should you use assertionFailure()?

The main difference between assertionFailure() and fatalError() is that assertionFailure is not executed on Release environment. That’s why you need to put return when unwrapping a nullable value if you want to stop the execution of code.

Conclusion

In conclusion, assertionFailure() is a function in Swift that is used to stop the execution of a program on Debug Environment. By using assertionFailure(), you can catch errors early in the development process and ensure that your code works correctly before it is released. And rest assurred, your app won’t crash because assertionFailure() is only called on Debug Environment.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!