#ifdef replacement in the Swift language

前端 未结 17 1970
名媛妹妹
名媛妹妹 2020-11-22 10:35

In C/C++/Objective C you can define a macro using compiler preprocessors. Moreover, you can include/exclude some parts of code using compiler preprocessors.

         


        
17条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:15

    As of Swift 4.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:

    • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
    • _isReleaseAssertConfiguration() (true when optimization is set to -O) (not available on Swift 3+)
    • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)

    e.g.

    func obtain() -> AbstractThing {
        if _isDebugAssertConfiguration() {
            return DecoratedThingWithDebugInformation(Thing())
        } else {
            return Thing()
        }
    }
    

    Compared with preprocessor macros,

    • ✓ You don't need to define a custom -D DEBUG flag to use it
    • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
    • ✗ Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)

      • these once removed, but brought back to public to lack of @testable attribute, fate uncertain on future Swift.
    • ✗ Using in if/else will always generate a "Will never be executed" warning.

提交回复
热议问题