How to use @available and #available and when to use it ?

How to use @available and #available and when to use it ?

In Swift, you use the @available attribute to control whether a declaration is available to use when building an app for a particular target platform. Similarly, you use the availability condition #available to execute code conditionally based on required platform and version conditions. Both kinds of availability specifier are also available in Objective-C.

Swift availability checking is most commonly used to mark sections of code that should target specific versions of iOS or other platforms. However, it’s also useful when you make Swift APIs for others to use, because you can use it to mark certain calls as deprecated or even obsoleted as needed.

Mark Availability
Use the API_AVAILABLE macro to add availability information in Objective-C:

@interface MyViewController : UIViewController
- (void) newMethod API_AVAILABLE(ios(11), macosx(10.13));
@end

This is equivalent to using the @available attribute on a declaration in Swift:

@available(iOS 11, macOS 10.13, *)
func newMethod() {
// Use iOS 11 APIs.
}

Check Availability

There are times when you really do need to use a newer feature, for example if you want to use UIStackView where it’s available but otherwise show a message to users asking them to upgrade. For this, Swift has #available, which lets you state that a certain block of code should only execute on specific versions of iOS.

Use the @available() keyword to check availability information in a conditional statement in Objective-C:

if (@available(iOS 11, *)) {
// Use iOS 11 APIs.
} else {
// Alternative code for earlier versions of iOS.
}

This is equivalent to the following conditional in Swift:

if #available(iOS 11, *) {
// Use iOS 11 APIs.
} else {
// Alternative code for earlier versions of iOS.
}

Discover more from CODE t!ps

Subscribe to get the latest posts sent to your email.

Scroll to Top

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading