Thursday, July 26, 2018

Conditional Compilation in Swift

Dave DeLong:

Settings in configuration files can be configured to have different values based on certain conditions (namely, the name of the SDK being used and/or the architecture being built).

This, combined with a certain build setting, gives us everything we need to have nicer conditional compilation.

[…]

Now we have something that’s much clearer and future-proof:

func isFeatureAvailable() -> Bool {
    #if BUILDING_FOR_SIMULATOR
        return false
    #else
        return true
    #endif
}

This uses the SWIFT_ACTIVE_COMPILATION_CONDITIONS build setting.

Dave DeLong:

Buried deep inside the Xcode Build Settings reference is a pair of obscure build settings: INCLUDED_SOURCE_FILE_NAMES and EXCLUDED_SOURCE_FILE_NAMES.

As their names suggest, these build settings allow you to specify additional files via your build configurations. When compiling, the exclusions happen first, and then the inclusions are applied, resulting in a final set of files passed to the compiler.

The values to these settings can be explicit paths to files, or they can be glob patterns (like *.swift). Since this is a build configuration file, substitutions work too: *.$(CURRENT_ARCH).c. And finally, since these are regular build settings, we can conditionalize the value based on the SDK.

He uses these to match platform qualifiers in the directory and filenames.

Comments RSS · Twitter

Leave a Comment