Checking API Availability in Swift 2

October 12th, 2015

Filed under: Mac Development, Xcode | Be the first to comment!

When developing Mac and iOS applications, the recommended approach to support older operating systems is to use the most recent SDK and set the deployment target to the earliest operating system your application supports. Until recently the problem with this approach is there was no way to tell at compile time if your code used anything that is not available on older operating systems. You had to run your application on older operating systems to make sure you weren’t using any unavailable technologies, classes, or functions.

Life got much easier for Swift developers with the releases of Swift 2 and Xcode 7. Swift 2 provides the #available and @available keywords that emit compiler errors if you use an API unsafely.

#available

The #available keyword works with if and guard statements. Supply an operating system version version, and the code inside the if or guard block executes only on machines capable of running the code. Suppose you have a Mac application that supports OS X 10.9 to 10.11. You have some code that uses something introduced in OS X 10.11. The code would look something like the following:

if #available(OSX 10.11, *) {
    // Make API call that was introduced in OS X 10.11.
}
else {
    // Code to run on OS X 10.9 and 10.10.
}

The asterisk as the second argument to #available tells the compiler to require the minimum deployment target for other platforms.

Things work similarly for iOS. The following code shows how to support an iOS 9 feature while also supporting older iOS versions:

if #available(iOS 9.0, *) {
    // Make API call that was introduced in iOS 9.
}
else {
    // Code to run on earlier iOS versions.
}

Using #available with a guard statement works best with code intended only for newer operating system versions. You can bail out and do nothing on older operating systems. The following is an example for OS X:

guard #available(OSX 10.11, *) else { return }
    // Make API call that was introduced in OS X 10.11

And for iOS:

guard #available(iOS 9.0, *) else { return }
    // Make API call that was introduced in iOS 9.

@available

The @available keyword lets you mark a function, method, or class as being available only on certain operating system versions. You supply the same information as #available: an operating system version and an asterisk. The following code shows how to use @available in a function:

@available(iOS 8.0, *)
func myFunctionThatUsesiOS8() {

}

And now a class example:

@available(OSX 10.10, *)
class MyClass {

}

Tags: ,


Leave a Reply

Your email address will not be published. Required fields are marked *