Use `assertionFailure()` and `preconditionFailure()` over `assert(false)`SW-W1021
The assert(false)
method is commonly used to indicate an unexpected code path, which should never occur. However, it has some issues that can lead to incorrect assumptions and bugs.
First, the assert()
function is generally used for debugging purposes, and it is compiled out of release builds. This means that assert(false)
statements will not be executed in production. Unfortunately, this can lead to undetected issues when the code is deployed to users.
Second, assert(false)
does not provide any information about the cause of the failure. It only indicates that an assertion has failed, but it does not provide any context or explanation. This can make it difficult to debug issues, especially when multiple assertions fail in the same code block.
Instead of using assert(false)
, it is recommended to use assertionFailure()
or preconditionFailure()
. These functions provide more information about the failure and cause the app to crash immediately in both debug and release builds.
Bad Practice
func foo(_ value: Int) {
if value < 0 {
assert(false)
}
// ...
}
Recommended
func foo(_ value: Int) {
if value < 0 {
assertionFailure("Negative value passed to foo()")
}
// ...
}