Search code examples
swiftxcodemacrosversioning

What's the Swift equivalent of Objective-C's "#ifdef __IPHONE_11_0"?


I want to use Xcode 9 to add iOS 11 code to my project while keeping the option to compile the project with Xcode 8 which only supports iOS 10.

In Objective-C I can do this by using a preprocessor directive to check if __IPHONE_11_0 is defined. Which will hide the code if I'm compiling with a Base SDK earlier than iOS 11. Like this:

#ifdef __IPHONE_11_0
    if (@available(iOS 11.0, *)) {
        self.navigationController.navigationBar.prefersLargeTitles = YES;
    }
#endif

Is there a way to do that in Swift?

if #available(iOS 11.0, *) doesn't work because that's a runtime check.


Solution

  • The iOS 11 SDK comes with Swift 3.2 (or Swift 4), so you can use a Swift version check to accomplish the same thing:

    #if swift(>=3.2)
        if #available(iOS 11.0, *) {
            …
        }
    #endif