Negate #available statement
In Swift 5.6, you can now do the following:
if #unavailable(iOS 15) {
// Under iOS 15
} else {
// iOS 15+
}
Or just the following depending on your case:
if #unavailable(iOS 15) {
// Under iOS 15
}
This is part of SE-0290: Negative availability.
I use a guard
for this:
guard #available(iOS 8.0, *) else {
// Code for earlier OS
}
There's slight potential for awkwardness since guard
is required to exit the scope, of course. But that's easy to sidestep by putting the whole thing into its own function or method:
func makeABox()
{
let boxSize = .large
self.fixupOnPreOS8()
self.drawBox(sized: boxSize)
}
func fixupOnPreOS8()
{
guard #available(iOS 8, *) else {
// Fix up
return
}
}
which is really easy to remove when you drop support for the earlier system.
It is not possible to have logic around the #available
statement.
Indeed, the statement is used by the compiler to infer what methods can be called within the scope it embraces, hence nothing can be done at runtime that would conditionally execute the block.
It is possible though to combine conditions, using a comma, as follows
if #available(iOS 8.0, *), myNumber == 2 {
// some code
}