Compiler directives in Swift

This post is going to list some of the most frequently used compiler directives in Swift, compatible in Swift 3/4/5. Someone might call this preprocessor directives, but they are the same concept.

Environment checking

This is the highly recommended and useful Compiler directives which I used quite often while coding. For example, you can tell the program to use different values for different environments:

var url = ""
#if DEBUG
// use localhost while under debug mode
url = "https://localhost"
#else
// use production url while under release
url = "production url"
#endif

// You can negate the flag
#if !RELEASE
// use localhost while under debug mode
url = "https://localhost"
#else
// use production url while under release
url = "production url"
#endif

Using the above code, you can then build and compile an IPA file, which will automatically use a different url based on the environment, so you don't have to build and compile two versions (Debug and Release).


Platform detection

When you want to cross apple platform:

#if os(OSX)
// compiles for OS X
#elseif os(iOS)
// compiles for iOS
#elseif os(tvOS)
// compiles for TV OS
#elseif os(watchOS)
// compiles for Apple watch
#endif

With the above code, it will automatically use the right code block if it is running on a different platform.


Warnings and Errors

It is quite strange that developer add warning and errors to the project themselves. But such tricks might be useful in some cases, such as adding a warning to remind yourself to improve some part of the code later on.

#warning("Needs improve on the performance")
#error("Needs remove the duplicated code")

Language check

// Check the Swift version
#if swift(<5)
#endif

Running device check

// Check environments like Simulator or Catalyst
#if targetEnvironment(simulator)
#endif

Module check

// Check if a module presents
#if canImport(UIKit)
#endif

There are also some other non directives but used quite often in the project, for example, It is quite common to see this in the project if it is trying support old SDK versions. such as iOS 10+.

if #available(iOS 10.0, *) {
}

Reference

comments powered by Disqus