Introducing Swift Power Assert

Hello everyone. I have created a Power Assert library using Swift's new macro feature.

Power asserts provide descriptive assertion messages for your tests, like the following examples:

#powerAssert(max(a, b) == c)
             |   |  |  |  |
             7   4  7  |  12

             |  |        |
             |  false    4
             [1, 2, 3]

#powerAssert("hello".hasPrefix("h") && "goodbye".hasSuffix("y"))
             |       |         |    |  |         |         |
             "hello" true      "h"  |  "goodbye" false     "y"

Swift macros are an experimental feature, so you need the pre-release Swift toolchain, but that is all you need to integrate it into a real project and use it as a test library.

Help needed!

Currently, Swift macros manipulate the SwiftSyntax syntax tree, and since the syntax tree does not contain type information, this library heuristically analyses the code for various code patterns.

However, since any code can be passed to the assert function, there must still be many unexpected patterns.

Try out this library and help us validate different code patterns. If you find a pattern that doesn't work correctly, please tell us about it in an issue on GitHub.



Super useful! I look forward to trying this out in my projects, and helping out with fixes if I find any issues

1 Like

I'm a big fan of Spock's assertion error messages. Any chance of changing the spelling to #expect(foo == bar) instead of #powerAssert? I just find it a bit verbose.

1 Like

Thanks, #expect seems good. Actually, I wanted to simply use #assert, but Swift's macros don't expand #assert, so I had no choice but to use #powerAssert.

The assert function is now called #expect. Keep #powerAssert as an alias for #expect.


Awesome! Looking forward to using it once I'm working on a 5.8 project :smiley:

1 Like

FYI, we've fixed the compiler bug, so in recent toolchains it's possible to use #assert.



Thank you. I am a little worried that if the Compile Time Assertion feature will be officially accepted, it will take precedence over the Compile Time Assertion feature than macro?
Or if Compile Time Assertion is accepted, it will use a different syntax?

If compile time assertions are accepted some day, they could use a different syntax.



Assert function is now #assert(). Very nice to have a simple API. I will keep #expect() and #powerAssert() as aliases for a while.


The online playground is now available.

This interactive platform allows you to effortlessly test and explore the functionalities of Swift Power Assert.