#ifdef replacement in the Swift language

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

    Yes you can do it.

    In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example:

    #if DEBUG
        let a = 2
    #else
        let a = 3
    #endif
    

    Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG entry.

    As usual, you can set a different value when in Debug or when in Release.

    I tested it in real code and it works; it doesn't seem to be recognized in a playground though.

    You can read my original post here.


    IMPORTANT NOTE: -DDEBUG=1 doesn't work. Only -D DEBUG works. Seems compiler is ignoring a flag with a specific value.

提交回复
热议问题