4

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?

Boon
  • 40,656
  • 60
  • 209
  • 315

1 Answers1

4

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).
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • In the guide, it does say: "the body of the if executes on the minimum deployment target specified by your target." – Boon Nov 24 '15 at 20:48
  • Yes - so is it potentially possible for the code to crash? For example, if I have minimum deployment target for WatchOS on iOS 9, but I have set the availability check to be iOS 10 and forgot to add watchOS version to it. – Boon Nov 25 '15 at 20:37
  • @Boon: Sorry, I don't get you. The minimum deployment target for watchOS can be for example "watchOS 2.0", not "iOS 9". And in any case, the compiler compare the availability of the APIs against the minimum deployment target. – Martin R Nov 25 '15 at 20:43
  • Sorry let me rephrase - say I am using an API that exists on iOS 10 and watchOS 3, but in my availability check, I only specify iOS 10 and *. The minimum deployment target is set to watchOS 2. Will the code crash when running on the watch? – Boon Nov 25 '15 at 20:44
  • 1
    @Boon: If you compile for watchOS, with minimum deployment target is set to watchOS 2 then the compiler will give an error if you use an API which is not available in watchOS 2. – Martin R Nov 25 '15 at 20:49