Swift vs. Obj-C: Target Conditionals
Justin Williams put together a list of what platform macros from TargetConditions.h
trigger each specific platform. The results are a mess. The worst one is that TARGET_OS_MAC
will target all of Apple’s platforms (macOS, iOS, watchOS, & tvOS) and TARGET_OS_IPHONE
is everything except macOS.
This is one of the most underrated improvements in Swift. Instead of
#if TARGET_OS_IPHONE
// iOS code
#else
// macOS code
#endif
we can use something more like
#if os(macOS)
// macOS code
#endif
The nice thing here that you don’t have to worry about if you are running on the simulator or not1.
Even better, starting with Swift 3 you can check for the existence of a framework. This is useful for frameworks that are supported on multiple platforms.
#if canImport(UIKit)
// iOS, tvOS, & watchOS
import UIKit
let color: UIColor
#elseif canImport(AppKit)
// macOS
import AppKit
let color: NSColor
#endif
These are small improvements, but they make writing code that runs on multiple platforms a lot easier.
- There is a separate check you can still make if you need to know that. ↩