#ifdef replacement in the Swift language

前端 未结 17 1706
名媛妹妹
名媛妹妹 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:42

    isDebug Constant Based on Active Compilation Conditions

    Another, perhaps simpler, solution that still results in a boolean that you can pass into functions without peppering #if conditionals throughout your codebase is to define DEBUG as one of your project build target's Active Compilation Conditions and include the following (I define it as a global constant):

    #if DEBUG
        let isDebug = true
    #else
        let isDebug = false
    #endif
    

    isDebug Constant Based on Compiler Optimization Settings

    This concept builds on kennytm's answer

    The main advantage when comparing against kennytm's, is that this does not rely on private or undocumented methods.

    In Swift 4:

    let isDebug: Bool = {
        var isDebug = false
        // function with a side effect and Bool return value that we can pass into assert()
        func set(debug: Bool) -> Bool {
            isDebug = debug
            return isDebug
        }
        // assert:
        // "Condition is only evaluated in playgrounds and -Onone builds."
        // so isDebug is never changed to true in Release builds
        assert(set(debug: true))
        return isDebug
    }()
    

    Compared with preprocessor macros and kennytm's answer,

    • ✓ 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
    • Documented, which means the function will follow normal API release/deprecation patterns.

    • ✓ Using in if/else will not generate a "Will never be executed" warning.

提交回复
热议问题