Show Menu

Looking to hire an app developer?

Submit your 30 day Job Listing for FREE

On June the 8th 2015, Apple announced Swift 2.0 at WWDC. This Swift 2.0 Tutorial will show you how to check API Availability using the new syntax #available.

In Swift 2 we have a new feature that lets us easily check if a feature is available on the current device and platform version running our app. So we can now essentially say ‘if this feature is available then we want to perform this code, otherwise do this’, the syntax is very straight forward. We will wrap this in a Swift If Statement like so:

if #available (iOS 9.0, OSX 10.11, *) {
    // Do some things with the cool new APIs
} else {
    // The new APIs are not available so do this
}

The new feature you can see there is called #available and we need to give it a couple of arguments, the first two in this case are the two platform versions we want to check for and then you will notice the *. So what’s that all about? That indicates to the compiler that we require the minimum deployment target for other platforms not specifically listed, and this is mandatory for control flow. If none of our list is satisfied then the else kicks in.

You can combine this with the new guard feature to bail out early:


guard #available(iOS 9.0, OSX 10.11, *) else { return}
    // Do some things with the cool new APIs

There is another tool available to us and that is to mark functions or even classes as being available only on certain platforms, we do this with @available


@available(iOS 9.0, *)
func myFunction() {
    // Do a bunch if things some things here with iOS 9 cool new features
}

So you can combine these in to something like this so you do not have to write the if statement over and over

@available(iOS 9.0, *)
func myFunction() {
    // Do this iOS 9 thing
    // Now do this iOS 9 thing
    // Celebrate our user having iOS  9
}

if #available (iOS 9.0, *) {
    myFunction()
} else {
    // Be sad because they have yet to upgrade to iOS 9
}

So that is how you use the new Swift 2.0 availability checking feature, a nice and simple but very useful feature that makes Swift 2.0 such a beautiful version.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

Web and Application Developer / Designer. I write about tools, techniques and tips for working with web and iOS technologies.

Comments

comments