Swift Availability Checking

Availability checking was already in use by Xcode. But with Swift 2.0 it has this feature built directly into the compiler. This ensures you will not be able to use unavailable APIs on a given deployment target.

Swift utilizes availability checking in two different ways. As a condition in an “if”, “guard”, or “while” statement, or as a declaration attribute.

Usage in a conditional statement:

Screenshot from The Swift Programming Language book.

The platform name may be any of the following.

Screenshot from The Swift Programming Language book.

The version number may contain major only, or major.minor.fix release numbers like 10.10.3. For example,

The * is required and says on any other platform the APIs should be available to your minimum deployment target.

If you haven’t yet, I highly recommend checking out my post on swift’s guard statement. It works great with availability checking and error handling. Here’s a futuristic example using the guard statement.

Look, I’m already supporting iOS X 😜

Usage as a declaration attribute:

Availability checking may also be applied to whole declarations using the @available syntax.

“You can apply multiple available attributes on a single declaration to specify the declaration’s availability on different platforms.” — Apple Inc. “The Swift Programming Language”

First you use one of the earlier specified platforms, or the * symbol. And then a comma seperated list of arguments including:

If you are only using the introduced argument such as in the example above, you may use the shorthand syntax.

Screenshot from The Swift Programming Language book.

Availability checking is great, especially if you are developing a public SDK for others to use. Here is a more involved example which makes use of the renamed and unavailable arguments.

This example shows how one might notifiy and require the user of MyProtocol to use the renamed version in a new release. The compiler even helps you out with a “Fix-it”!

If you want, you can check out Session 411: Swift in Practice. It includes an in depth look at Swift’s new availability checking feature.

Happy Coding

Recommend and follow me @iJoeCollins on Twitter