What is swift replacement of traditional c-style #error keyword?
I need it to raise compile-time error when pre-defines failed:
#if CONFIG1
...
#elseif CONFIG2
...
#else
#error "CONFIG not defined"
#endif
What is swift replacement of traditional c-style #error keyword?
I need it to raise compile-time error when pre-defines failed:
#if CONFIG1
...
#elseif CONFIG2
...
#else
#error "CONFIG not defined"
#endif
On
The main idea of #error is causing a compilation error when something is missing, as swift doesn't have yet a similar preprocessor statement, just force the compilation error, like this code.
#if CONFIG1
...
#elseif CONFIG2
...
#else
fatalError("CONFIG not defined")
callingANonExistingFunctionForBreakingTheCompilation()
#endif
Remember that C/C++ won't verify the syntax of non-matching blocks, but Swift will, so this is the reason I'm calling a function rather than just writing a message.
Another option is using your own tag for generating the error and checking it before its compilation, like what this guy did here
On
Great news - if you're using Swift 4.2 or newer you can now use #error() and #warning()
For example:
let someBoolean = true
#warning("implement real logic in the variable above") // this creates a yellow compiler warning
#error("do not pass go, do not collect $200") // this creates a red compiler error & prevents code from compiling
Check out the implemented proposal here https://github.com/apple/swift-evolution/blob/master/proposals/0196-diagnostic-directives.md
According to the documentation, there is no specific #error macro. However it is possible to the program from compiling.
The way to do this is to define the variable you will be using inside the the #if/#endif clause. If no clause matches then the variable will be undefined and the program will not compile.
Raising an error at the failure site is possible with workarounds. Entering a plain string in the #else clause, which will generate a syntax error. Using
@availablewill generate a compiler warning.