6 tips on how to use compiler directives in Swift

Needone App
2 min readSep 8, 2020

--

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:

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:

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)
// your code here
#endif

Running device check

// Check environments like Simulator or Catalyst 
#if targetEnvironment(simulator)
// your code here
#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

Originally published at https://needone.app on September 8, 2020.

--

--

No responses yet