Conditional Compilation with Swift

Occasional you’ll need to write code blocks that are specific to an OS (as I’ve found Swift on Linux and on Mac OS is not always 100% in sync with features).

In which case we can use conditional compilation blocks, such as

#if os(Linux)
// code specific to Linux
#elseif os(Windows)
// code specific to Windows
#endif

The os() condition accepts, macOS, iOS, watchOS, tvOS, Linux and Windows.

Other conditions include architecture arch() with options i386, x86_64, arm and arm64.

Swift also allows supports canImport which can be used to check if a module is available, like this

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

See Conditional Compilation Block from the Swift language manual for a full list of conditions.