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
#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.

--

--

--

needone.app

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

Recommended from Medium

SwiftUI: List and LazyVStack. How to use and support iOS 13 and 14 versions

Why Don’t My Pods Compile With Mac Catalyst and How Can I Solve It?

Swift Text To Speech Synthesizer

CoolStar demonstrates sandbox escape on iOS 15.0–15.1.1 and explores the remaining jailbreak steps

Designing An API Service Manager and API Data Model in Swift for Weather Application

How to Upgrade iPhone/iPad Safari to Summarise Webpages Using ML

SwiftUI: StateObject vs ObservableObject

Introduction to SwiftUI

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

needone.app

More from Medium

Batch Convert XCode String files, from utf-16 to utf-8

Best way to use Font Name using enum in iOS-Swift

Managing Concurrency With Swift Task Groups

Create Universal Framework