What is the beauty of # in Swift? It means different things in different parts of the project.
Using # in Podfile comments line. In code, # added to “if” change behavior of it.
Standard “if” checks variable runtime and decides whether it’s correct or not. What about checking system version or Swift version? For that, we can use #if.
#if allows checking for example Swift version, current architecture or operating system.
Every time when we open #if we have to close it using #endif, otherwise, an error will occur.
Let’s see for what we can use #if.
Operating system check:
#if os(iOS)
print(“Code runs on iOS”)
#elseif os(macOS)
print(“Code runs on macOS”)
#elseif os(watchOS)
print(“Code runs on watchOS”)
#elseif os(tvOS)
print(“Code runs on tvOS”)
#endif
Architecture check:
#if arch(i386)
print(“Code runs on iOS architecture”)
#elseif arch(x86_64)
print(“Code runs on x86_64 architecture”)
#elseif arch(arm)
print(“Code runs on arm architecture”)
#elseif arch(arm64)
print(“Code runs on arm64 architecture”)
#endif
Swift version check:
#if swift(<4)
print(“Swift earlier then 4 is used”)
#elseif swift(>=5)
print(“Swift 5 or newer is used”)
#else
print(“Swift 4.x is used”)
#endif
Compiler version check:
#if compiler(<4)
print(“Compiler earlier then 4 is used”)
#else
print(“Compiler 4 or newer is used”)
#endif
Module availability:
#if canImport(UIKit)
print(“UIKit is avaialble”)
#else
print(“UIKit isn’t avaible”)
#endif
Code runs in debug mode:
#if DEBUG
print(“Code runs in debug mode”)
#endif
Code runs on simulator:
#if targetEnvironment(simulator)
print(“Code runs on Simulator”)
#endif
There are some logic operations are also avaible, such as !, && and ||.
#if os(iOS) && canImport(AppKit)
print(“Something went wrong because AppKit isn’t available on iOS”)
#endif
If you need to create custom compilation check, read this post.