How to fail in Swift.
Fatal Error
Unconditionally print a `message` and stop execution.
fatalError("Goodbye!") fatalError()
Assert
Traditional C-style assert with an optional message. Use these to test assumptions and locate design errors during development.
assert(false) assert(false, "Oops") assertionFailure() assertionFailure("Oops")
- Program execution ends on false assertions in playgrounds and -Onone.
- Assertions are not evaluated in -O (default Release).
- For -Ounchecked, the optimizer tries to assume the assertion would evaluate to true. If not, it is a “serious programming error”.
Precondition
Unlike assertions, preconditions are checked and will stop an app in release mode. Use these sparingly. With great failure comes great responsibility.
precondition(false) precondition(false, "Oops") preconditionFailure() preconditionFailure("Ooops")
- A fail stops to a debuggable state in Debug (-Onone) and playgrounds.
- Ends execution in release (-O).
- Same deal as assert for -Ounchecked.
Abort and Exit
Most commonly used for command line apps, abort() produces abnormal process termination.
@noreturn func abort()
Use exit() for traditional exit code support, which can then be tested in shell scripts.
@noreturn func exit(_: Int32)
Throwing
It’s entirely possible to throw or catch a recoverable error and continue execution. If that’s not a viable solution, find the best way to prepare for a clean termination and then perform a program exit.
enum Failure : ErrorType { case Fail } do { throw Failure.Fail } catch { // clean up shop NSLog("App failure") // prints to system console fatalError("\(error)") }
Comments are closed.