Checking API Availability in Swift
In a previous article I explained how to set up your Xcode projects to support older versions of iOS and macOS. But I didn’t explain how to use new functions on new iOS and macOS versions and older functions on older systems.
Swift provides two statements to help support older OS versions: #available
and @available
.
#available
The #available
keyword works with if
and guard
statements. Supply an operating system version version, and the code inside the if
block runs only on suitable systems.
Let’s work through an example. Apple added the NSPersistentContainer
class in iOS 10 and macOS 10.12 to simplify setting up the Core Data stack. You would like to use NSPersistentContainer
on systems that have the class and not use it on older versions of iOS and macOS. The following example shows how to use NSPersistentContainer
on systems running iOS 10 and later:
if #available (iOS 10, *) {
// Use NSPersistentContainer to set up Core Data stack
} else {
// Set up the Core Data stack the old way
}
The asterisk as the second argument to #available
tells the compiler to require the minimum deployment target for other platforms. The minimum deployment target is the earliest version of iOS or macOS that can run your app.
The following code shows how to use NSPersistentContainer
on systems running macOS 10.12 and later:
if #available (OSX 10.12, *) {
// Use NSPersistentContainer to set up Core Data stack
} else {
// Set up the Core Data stack the old way
}
Apple added the #available
statement before changing the name of the Mac operating system from OS X to macOS.
If you have some code that should run only on later versions of iOS or macOS, use #available
with a guard
statement. By using #available
with guard
, your code can exit if it’s running on an older version of iOS or macOS.
guard #available(iOS 11, *) else {
// Exit on iOS 10 and earlier
return
}
// Call the functions added in iOS 11.
@available
Place @available
in front of a function or class to make that function or class available only on supported iOS and Mac versions. Like #available
, supply an operating system version. The following code shows how to use @available
with a function:
@available(iOS 12, *)
func myFunctionThatRequiresIOS12() {
}
The following code uses @available
with a class:
@available(OSX 10.13, *) {
class MyHighSierraClass: NSObject {
}