Unavailability condition
Unavailability condition êŽë š
Available from Swift 5.6
SE-0290 (apple/swift-evolution
) 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 (signalapp/Signal-iOS
) common (videolan/vlc-ios
) workaround (ProtonMail/ios-mail
), 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.