@ Available and # available in Swift,
The availability concept is introduced in Swift 2.0. You can use functions, classes, protocols, etc.@available
Declare that these types of lifecycles depend on specific platforms and operating system versions. While#available
It is used in judgment statements (if, guard, while, etc.) to implement different logic on different platforms.
@ Available usage
@available
Put it in front of a function (method), class, or protocol. Indicates the platforms and operating systems applicable to these types. Let's look at the following example:
@available(iOS 9, *)func myMethod() { // do something}
@available(iOS 9, *)
Must contain at least 2 feature parameters, of whichiOS 9
Indicates that it must be in iOS 9 or later versions. If your deployed platform includes iOS 8, the compiler reports an error after calling this method.
Another feature parameter: asterisk (*), indicating that all platforms are included. Currently, the following platforms are available:
- IOS
- IOSApplicationExtension
- OSX
- OSXApplicationExtension
- WatchOS
- WatchOSApplicationExtension
- TvOS
- TvOSApplicationExtension
Generally, if there are no special cases*
Indicates the entire platform.
@available(iOS 9, *)
Is a short form. The full write format is@available(iOS, introduced=9.0)
.introduced=9.0
The parameter indicates that the Declaration is introduced from 9.0 on the specified platform (iOS. Why can I use the simplified form? When onlyintroduced
Such a parameter can be abbreviated to the preceding abbreviated form. Likewise: @ available (iOS 8.0, OSX 10.10, *) is also possible. It indicates the availability on multiple platforms (iOS 8.0 and above; OSX 10.10 and above) at the same time.
In addition,@available
Other parameters can be used:
Deprecated = version number
: Indicates that a specified platform version expires.
Obsoleted = version number
: Deprecated a specific version of the specified platform,deprecated
Yes, you can continue using it, but it is not recommended,obsoleted
Indicates that the call will cause compilation errors.) This statement
Message = Information Content
: Provide some additional information
unavailable
: The specified platform is invalid.
Renamed = new name
: Rename Declaration
For more information about the preceding parameters, see the official documentation.
# Available
# Available is used in the code block of conditional statements to determine different platforms and perform different logic processing, such as: if # available (iOS 8 ,*) {// run on iOS 8 and above} guard # available (iOS 8, *) else {return // return directly for systems below iOS 8}
Stackoverflow Problems
- Difference between @ available and # available in swift 2.0: @ available and # available
The post also mentions a problem:@available
Is it determined during compilation? While#available
Is it a running behavior?