Using New API Features in Swift While Supporting Older OS Versions
Every year at WWDC Apple adds new features to their developer SDKs. Usually these new features require the upcoming version of iOS and macOS. You would like to use the new features while also supporting older versions of iOS and macOS. How do you do this?
Apple provides two Swift keywords to use both new code and old code in your apps: #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 (or after the guard
) executes only on machines capable of running the code. Use the else
block for code to run on older operating systems. The following example shows how to run one block of code on iOS 15 and another block on earlier iOS versions:
if #available(iOS 15, *) {
// iOS 15 code here
} else {
// Code for earlier iOS versions
}
The following example shows how to run one block of code on macOS 12 and another block on earlier macOS versions:
if #available(macOS 12, *) {
// macOS 12 code here
} else {
// code for earlier Mac versions
}
What Does the Asterisk Do?
The asterisk in the last argument to #available
tells the compiler to require the minimum deployment target for other platforms. You must always supply the asterisk to support future platforms Apple may add.
Checking for Multiple Platforms
Suppose you have a multiplatform SwiftUI project and you want to conditionally run code for iOS 15 and macOS 12. Supply the second platform operating system as an additional argument to #available
. The following example checks for both iOS 15 and macOS 12:
if #available(iOS 15, macOS 12, *) {
// Code for newer systems here
} else {
// Code for older systems here
}
guard Statements
Using available
with a guard
statement works best with code that should only run on newer versions of iOS and macOS. You can exit and do nothing on machines running on older operating systems.
guard #available(iOS 15, *) else { return }
// iOS 15 code here
@available
The @available
keyword lets you mark a function, struct, or class as being available only on certain versions of iOS and macOS. Supply the same information as #available
: an operating system version and an asterisk. The following code demonstrates the use of @available
in a function:
@available(iOS 15, *)
func myiOS15Function() {
}
Struct example:
@available(macOS 12, *)
struct MyMacOS12Struct {
}
Class example with multiple platforms:
@available(iOS 15, macOS 12, *)
class MyMultiplatformClass {
}