TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Unavailability condition

Available from Swift 5.6

Paul Hudson      @twostraws

SE-0290 introduces an inverted form of #available called #unavailable, which will run some code if an availability check fails.

This is going to be particularly useful in places where you were previously using #available with an empty true block because you only wanted to run code if a specific operating system was unavailable. So, rather than writing code like this:

if #available(iOS 15, *) { } else {
    // Code to make iOS 14 and earlier work correctly
}

We can now write this:

if #unavailable(iOS 15) {
    // Code to make iOS 14 and earlier work correctly
}

This problem wasn’t just theoretical – using an empty #available block was a fairly common workaround, particularly in the transition to the scene-based UIKit APIs in iOS 13.

Apart from their flipped behavior, one key difference between #available and #unavailable is the platform wildcard, *. This is required with #available to allow for potential future platforms, which meant that writing if #available(iOS 15, *) would mark some code as being available on iOS versions 15 or later, or all other platforms – macOS, tvOS, watchOS, and any future unknown platforms.

With #unavailable, this behavior no longer makes sense: would writing if #unavailable(iOS 15, *) mean “the following code should be run on iOS 14 and earlier,” or should it also include macOS, tvOS, watchOS, Linux, and more, where iOS 15 is also unavailable? To avoid this ambiguity, the platform wildcard is not allowed with #unavailable: only platforms you specifically list are considered for the test.

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.6…

Download all Swift 5.6 changes as a playground Link to Swift 5.6 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.