Write Platform-Specific Code Using Conditional Compilation
Written by Team Kodeco
In developing a cross-platform SwiftUI application, you may need to fine-tune the app’s behavior or appearance for individual platforms. SwiftUI provides a way to handle such platform-specific customizations without creating separate files for each platform, thanks to conditional compilation.
Conditional compilation is a feature of Swift that allows you to include or exclude parts of the code based on specific conditions. This feature can be used to compile certain portions of the code based on the target operating system.
To illustrate how conditional compilation works in SwiftUI, see the following example:
struct ContentView: View {
@State private var isOn = false
var body: some View {
VStack {
Toggle(isOn: $isOn) {
Text("Allow notifications")
}
#if os(macOS)
.toggleStyle(.checkbox)
#endif
}.padding()
}
}
In this SwiftUI code snippet, you have a Toggle
that controls whether to show a hypothetical “Allow notifications” Text
view. The toggle’s style is set to .checkbox
but only for macOS using conditional compilation. This way, you utilize a UI feature, CheckboxToggleStyle
, that’s unique to macOS when your app runs on that platform, while falling back to the default Toggle
style on other platforms.
Here’s what the Toggle
looks like on macOS:
While here’s what it looks like on iOS:
Conditional compilation is like having a multi-tool: you use the correct code to fit the platform you’re currently targeting, keeping your codebase clean and efficient without the necessity for platform-specific files.