GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.