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:

1 #if <condition>
2 #elseif <condition>
3 #else
4 #endif

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:

1 #if os(OSX)
2     typealias Color = NSColor
3 #else
4     typealias Color = UIColor
5 #endif

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:

1 @IBAction func someButtonPressed(sender: AnyObject!) {
2     #if FREE_VERSION
3         // 弹出购买提示,导航至商店等
4     #else
5         // 实际功能
6     #endif
7 }

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.

参考文章:Conditional Compilation