#28: #if and Other #ifdef Replacements in Swift

Swift does not use the C preprocessor, but it has built-in conditional compilation directives.

#if os(iOS)
print("Running on iOS")
#elseif os(macOS)
print("Running on macOS")
#endif

#if DEBUG
print("Debug build")
#endif

You can also branch on architecture and imported modules:

#if arch(arm64)
// arm64-specific code
#endif

#if canImport(UIKit)
import UIKit
#endif

So the Swift replacement for #ifdef is usually just #if with one of these conditions or a custom build flag.


I'm also on Twitter and GitHub.

Subscribe via RSS.