6 tips on how to use 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:

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

Running device check

// Check environments like Simulator or Catalyst 
#if targetEnvironment(simulator)
// your code here

Module check

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

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, *) { 


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





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Views and Voice Control Accessibility in SwiftUI


Complete guide on custom class/struct comparison

SwiftUI: How to take screenshot of ScrollView Content?

Building a To-Do App in Swift — Part 6

WWCD 2021 — The latest update on iOS and iPadOS 15 — Missed dev community’s expectation

Swift 101. Convert coordinates to city names and back

How to build a Progress Bar with SwiftUI Animations

Dependency Management in iOS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Needone App

Needone App


More from Medium

How to Intercept Http requests in Charles proxy for iPhone

Measurements in Swift: Enhanced and Simplified Again

What is declarative and imperative way of programming in Swift?

A Text Tale. My Worst Bug in 40 Years