UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free 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.