Panic in Swift
In Swift, we use fatalError()
as an equivalent to Go’s panic()
. It immediately terminates the program and prints an error message.
Running this program will cause it to terminate, print an error message and stack trace, and exit with a non-zero status.
When the first fatalError
in main
is triggered, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first fatalError
.
Note that unlike some languages which use exceptions for handling of many errors, in Swift it’s idiomatic to use error-indicating return values (via throws
and do-catch
blocks) wherever possible. The fatalError
function should be used sparingly, typically only for debugging or in situations where recovery is impossible.
Swift also provides assert()
and precondition()
functions which can be used for runtime checks that are disabled in release builds, offering a way to catch programming errors early in development without impacting release performance.