Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 323
Matthias Bauch Avatar asked Jun 07 '17 23:06

Matthias Bauch


People also ask

How similar is Swift to Objective-C?

According to Apple, Swift is approximately 2.6 times faster than Objective C. The speed calculated generally relates to the speed of coding. Swift's syntax is much more simple and direct than Objective-C. This enables developers to focus on the core part of the code rather than the rules on which the codes are based.

Is Swift based on Objective-C?

Swift is a programming language that was released by Apple in 2014. It was created as an advancement of Objective-C, a programming language used for iOS development. The language is currently used for products with iOS 7 as well as MacOS 10.9 or higher.

Is Swift a superset of Objective-C?

What you should notice, though, is that there are two important differences between the Objective-C and Swift languages: Swift is not a strict superset of the C language. Swift is statically typed, not dynamically typed.

Is Objective-C more powerful than Swift?

Objective-C has a superior runtime compared to Swift. It's probably going to be several years before Swift can catch up. If you're using powerful SDKs, Objective-C is also your best option here as well. I'd still recommend that new developers start off learning Swift.


3 Answers

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
like image 127
Lily Ballard Avatar answered Oct 24 '22 06:10

Lily Ballard


This is the solution suggested by Apple:

if #available(iOS 11.0, *) {
    // iOS 11 specific stuff here
} else {
    // non iOS 11 stuff here
}

Please refer to this resource (watch video on mark 6:50 for more details)

like image 6
pesch Avatar answered Oct 24 '22 05:10

pesch


If you want to put the condition outside of the function, you could do it like below.

@available(iOS 11.0, *)
func functionName() {
 // function contents
}
like image 3
Carly Avatar answered Oct 24 '22 06:10

Carly