Boon
Boon

Reputation: 41510

Last argument of Swift #availability check

Swift programming language guide has this to say regarding the last argument in #availability check:

if #available(iOS 9, OSX 10.10, *) {
    // Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X
} else {
    // Fall back to earlier iOS and OS X APIs
}

The last argument, *, is required and specifies that on any other platform, the body of the if executes on the minimum deployment target specified by your target.

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.1).” iBooks. https://itun.es/us/jEUH0.l

I think I am not understanding this correctly - if I intend for the code to execute in iOS 9 only and my minimum deployment target is 8, won't that crash my app when running on other platforms and the code executes on the minimum deployment target?

Upvotes: 4

Views: 518

Answers (1)

Martin R
Martin R

Reputation: 539975

The last argument * does not indicate that the body executes on other versions of iOS or OS X, such as iOS 8.

It indicates that the body executes on the minimum deployment target on other platforms like watchOS or tvOS. Currently known platforms are listed under "Declaration Attributes" in "Attributes" in the Swift documentation:

    iOS
    iOSApplicationExtension
    OSX
    OSXApplicationExtension
    watchOS
    watchOSApplicationExtension
    tvOS
    tvOSApplicationExtension

The last argument * is required to handle all platforms not explicitly listed, and for future platforms. In your example,

if #available(iOS 9, OSX 10.10, *) {

} 

the block executes

  • on iOS >= 9, when running on the iOS platform,
  • on OS X >= 10.10, when running on the OS X platform,
  • on the respective minimum deployment target when running on any other platform (e.g. watchOS).

Upvotes: 4

Related Questions