Friday, March 4, 2016 [Tweets] [Favorites]

Swift Asserts

Mike Ash (comments):

Some people prefer to only have asserts in debug builds, under the theory that it’s good to have checks when debugging, but it’s best not to crash the app out in the real world with real users. However, the error is present regardless of the presence of the assert that checks for it, and if it’s not caught right away it’s just going to cause havoc down the road. It’s much better to fail quickly and obviously when it’s practical to do so.

[…]

There is one missing piece from the Swift version of assert. In the simple C version above, the expression for the failed assertion is printed by using #condition to get a stringified version of that parameter. Unfortunately, there is no equivalent in Swift, so while Swift can print the file and line number where the failure occurred, it’s not able to print the expression that was supposed to be true.

[…]

By using @autoclosure for the message argument, assert can avoid evaluating the message expression unless the assert actually fails.

[…]

That means that the full bodies of the various assert functions are saved, in an intermediate form, into the standard library module. Those bodies are then available to be inlined wherever you call them. Since they’re inlined, they have access to the context in which they’re compiled, and the optimizer can remove them entirely when it’s warranted.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment