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.
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.
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.
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.
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.
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
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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With