bri*_*dir 9 configuration compiler-errors predefined-macro swift
什么是传统c风格#error关键字的迅速替代?
当预定义失败时,我需要它来引发编译时错误:
#if CONFIG1
...
#elseif CONFIG2
...
#else
#error "CONFIG not defined"
#endif
Run Code Online (Sandbox Code Playgroud)
好消息 - 如果您使用的是 Swift 4.2 或更高版本,您现在可以使用#error()和#warning()
例如:
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
Run Code Online (Sandbox Code Playgroud)
在此处查看实施的提案https://github.com/apple/swift-evolution/blob/master/proposals/0196-diagnostic-directives.md
根据文档,没有特定的 #error 宏。然而,该程序有可能无法编译。
执行此操作的方法是定义将在 #if/#endif 子句中使用的变量。如果没有子句匹配,则变量将是未定义的,程序将无法编译。
通过解决方法可以在故障站点引发错误。在#else子句中输入纯字符串,这将产生语法错误。使用@available将生成编译器警告。
#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"]
Run Code Online (Sandbox Code Playgroud)