Skip to content

Using Swift's @available attribute

Swift, iOS Development, Xcode1 min read

If you are developing an app for iOS, you may need to ensure that your code is compatible with different versions of the operating system. For example, if you are using a new feature that was introduced in iOS 15, but you want your app to also work on devices running iOS 14, you need to use conditional statements to determine whether that feature is available on the current version of iOS.

Thankfully, Swift provides an easier way to handle these situations using the @available attribute. The @available attribute allows you to mark parts of your code as being available only on certain versions of iOS. This helps prevent runtime errors in situations where you try to call APIs that do not exist on the user's device.

Let's look at some examples of how to use the @available attribute in Swift:

1if #available(iOS 15, *) {
2 // Use new API only available on iOS 15 or later
3} else {
4 // Fallback for earlier iOS versions

In this example, we check if the device is running iOS 15 or later. If it is, we use the new API that is only available on iOS 15 or later. Otherwise, we fallback to using another method that is available on earlier iOS versions.

1@available(iOS 15, *)
2func myFunction() {
3 // Function only available on iOS 15 or later

In this example, we define a function that is only available on iOS 15 or later. If you try to call this function on a device running an earlier version of iOS, you will get a compile-time error.

1@available(iOS, introduced: 14)
2func myFunction() {
3 // Function introduced in iOS 14

In this example, we mark a function as being introduced in iOS 14. This means that the function is available on all versions of iOS after 14.0, but not on earlier versions.

The @available attribute can also be used with other platforms such as macOS, watchOS, and tvOS. Additionally, there are several options you can use with the attribute, including the ability to specify the minimum deployment target, the maximum deployment target, and whether an API has been deprecated.

In conclusion - Swift's @available attribute is a powerful tool that allows you to write code that is compatible with multiple versions of iOS. By using the attribute, you can ensure that your app does not crash on devices running older versions of iOS, while still taking advantage of new features on newer devices.