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
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
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
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 @available
will generate a compiler warning.
#if CONFIG1
let config = // Create config 1
#elseif CONFIG2
let config = // Create config 2
#else
// Compilation fails due to config variable undefined errors elsewhere in the program.
// Explicit syntax error to describe the scenario.
Config not specified.
// This generates a compiler warning.
@available(iOS, deprecated=1.0, message="Config not defined")
#endif
// Use config here, e.g.
let foo = config["fooSize"]