Friday, May 20, 2016

Swift Assertions

Andy Bargh:

If we dive into a bit more of the detail behind assertions in Swift, we find that the Swift language actually supports five, different types of assertion. These are:
assert()
precondition()
assertionFailure()
preconditionFailure()
fatalError()

Each of these assertions behave slightly differently and in the majority of cases the optimisation level that the code is compiled with has a direct effect on whether they are evaluated or not.

Update (2017-03-15): Previously: precondition vs. assert in Swift.

2 Comments RSS · Twitter


Beware that the precondition function, that targets the Release configuration, *does not* output failure message in the crash logs, unlike fatalError. This prevents libraries that use preconditions to provide a meaningful message whenever they validate their function inputs, and leaves their users naked with blank errors that don't say what's wrong. Today it's better to use fatalError when you write a library. See https://bugs.swift.org/browse/SR-905 for more information.


@Gwendal Thanks! That is really too bad. I hope they change it.

Leave a Comment