This article will help you to understand the difference between #available and @available in Swift.
Swift, Apple’s programming language, provides developers with powerful tools to handle version-specific code and ensure compatibility across different iOS, macOS, watchOS, and tvOS platforms. Two essential constructs for managing API availability and versioning are #available
and @available
. In this tutorial, we will explore the differences between these two keywords and when to use each.
#available
#available
is a build-time construct used for checking the availability of APIs on specific platforms. It is commonly used in conjunction with conditional statements to execute code based on the availability of certain features in the runtime environment.
Syntax:
if #available(iOS 14, macOS 11.0, *) { // Code specific to iOS 14 and macOS 11.0 } else { // Fallback code for earlier versions }
Explanation:
- The
#available
keyword is followed by a list of platforms and their corresponding minimum version numbers. - The
*
wildcard is used to represent any future versions not explicitly specified.
Example:
if #available(iOS 14, macOS 11.0, *) { // Use iOS 14 and macOS 11.0 APIs // ... } else { // Fallback code for earlier versions // ... }
@available
@available
is an attribute used to annotate declarations (classes, methods, properties, etc.) with information about their availability on different platforms and versions. It is primarily a runtime construct, as it provides information about the availability of specific APIs during the execution of the code.
Syntax:
@available(iOS 14, macOS 11.0, *) class MyViewController: UIViewController { // Code for MyViewController }
Explanation:
- The
@available
attribute is applied to the declaration of a class, method, property, etc. - It specifies the platforms and their minimum version numbers where the annotated declaration is available.
Example:
@available(iOS 14, macOS 11.0, *) class NewFeatureViewController: UIViewController { // Code specific to iOS 14 and macOS 11.0 // ... }
Summary
In summary, #available
and @available
are constructs in Swift used for managing version-specific code and ensuring compatibility across different platforms.
#available
is used at build time within conditional statements to control the execution of code based on the availability of specific APIs on different platforms and versions.@available
is an attribute applied to declarations, providing information about the availability of specific APIs at runtime. It allows developers to annotate classes, methods, or properties with version-specific details, enabling the compiler to emit warnings or errors when inappropriate APIs are used.
Choose #available
for build-time conditional checks and executing code based on platform versions, and use @available
to annotate declarations with version-specific information at runtime. Understanding these constructs is essential for writing robust and version-compatible Swift code.