In C and Objective-C, we can use #if or #ifdef to control the compilation flow. It would be a great way if we want to omit the code by some conditions. There is no define in Swift, so there is no way to use #ifdef to check if a symbol is already defined or not. But Swift does reserve some simple mechanism to control the compilation content.

The #if is living in Swift, although not so popular-used now:

#if <condition>

#elseif <condition>



Of course, #elseif and #else is optional.

However, the <condition>s can be used in these statements are limited. There are several built-in conditions in Swift for the platforms and architectures you are targeting. By the combination of these conditions, we can decide what code to compile in a specified environment:

Method Parameter
os() OSX, iOS
arch() x86_64, arm, arm64, i386

The methods and parameters are all case-sensitive. Take an example, if we want to write a single color class for iOS and Mac, the first step would be creating a typealias for each. Conditional compilation would do well here:

#if os(OSX)
    typealias Color = NSColor
    typealias Color = UIColor

As parameters for arch(), arm and arm64 is only for real iOS device. When you select iOS simulator as your build target, i386 and x86_64 will be used on your Mac.

You can also use some customized symbol as a condition as well. For example, if we want to divide the paid version and the free version for the same target in an app, and do something only when in paid version, we can write this code:

@IBAction func someButtonPressed(sender: AnyObject!) {
        // Paid version prompt, navigate to AppStore, etc.
        // Real feature

We have to set FREE_VERSION for the project to make it available for use. In the Build Setting of app target, we can find an item with the name of "Other Swift Flags" in "Swift Compiler - Custom Flags" section. Add -D FREE_VERSION will do the trick and your code should be compiled following the #if condition now.