Conditional Compilation in Swift: Making Cross-Platform Apple Apps Work


I am currently building an app the will exist across multiple apple platforms (MacOS, iOS and iPadOS) and during this process I noticed that some features won’t work on other apple platforms.
For example I was building a feature that required camera access for my ios app.
The Problem: Different devices work differently!
iPhones/iPads: Have cameras, can take photos
Mac computers: Might not have cameras, work differently
Apple Watch: Definitely can't take photos!
Unfortunately, the iOS Simulator runs in a sandboxed environment that doesn't have access to macOS hardware due to apple’s strict security policies.
We can use conditional compilation blocks to prevent compiling for specific enivronments such as Simulator.
#if targetEnvironment(simulator)
// Camera does not work on the simulator
isCameraAvailable = false
#else
isCameraAvailable = UIImagePickerController.isSourceTypeAvailable(.camera)
#endif
}
#endif
}
What it does:
#if targetEnvironment(simulator)
- This checks if the app is running in the iOS Simulator (not on a real device)
If running in Simulator: Sets
isCameraAvailable = false
because the iOS Simulator cannot access the Mac's camera hardware.If running on real device: Uses
UIImagePickerController.isSourceTypeAvailable(.camera)
to check if the device actually has a working camera.
You can also use conditional compilation to:
Require a minimum operating system version for a feature
This would limit your apps minimum deployment target withing a specific range of operating systems.
/// Swift
if #available(iOS 15.4.1, *) {
// On iOS, this branch runs in versions 15.4.1 and greater.
// On any other OS, this branch runs in any version of that OS.
} else {
// This branch runs in earlier iOS versions.
}
To learn more about conditional compilation check out Apple Documentation.
Subscribe to my newsletter
Read articles from Clement Lumumba directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Clement Lumumba
Clement Lumumba
iOS Engineer