#ifdef replacement in the Swift language

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

    As stated in Apple Docs

    The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

    I've managed to achieve what I wanted by using custom Build Configurations:

    1. Go to your project / select your target / Build Settings / search for Custom Flags
    2. For your chosen target set your custom flag using -D prefix (without white spaces), for both Debug and Release
    3. Do above steps for every target you have

    Here's how you check for target:

    #if BANANA
        print("We have a banana")
    #elseif MELONA
        print("Melona")
    #else
        print("Kiwi")
    #endif
    

    Tested using Swift 2.2

提交回复
热议问题