Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

A Toggle with a checkbox style on macOS.
A Toggle with a checkbox style on macOS.

While here’s what it looks like on iOS:

A Toggle with a default style on iOS.
A Toggle with a default style 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.