1

I am using below code but getting the warning,

bool versionSupports = (@available(iOS 10, *));

@available does not guard availability here; use if (@available) instead

There is a solution where I can use

if (@available(iOS 10, *)){
//compile
}else{
//fallback
}

I was curious, why an output is placeable inside if() condition but not placeable into a boolean variable?

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256

3 Answers3

5

@available(iOS 10, *) is not a BOOL expression. It does not return an indication of whether the code is being run on that version of iOS or not.

It needs to be in the form of:

if (@available(iOS 10, *)) {
    // Code that requires iOS 10 or later
} else {
    // Code for iOS 9 or earlier
}

If you want a variable that indicates whether the current device is running iOS 10 or later then you can do something like:

BOOL versionSupports = [UIDevice currentDevice].systemVersion.floatValue >= 10;

You may also find Objective-C @available guard AND'ed with more conditions helpful depending on your needs.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Be a bit careful with float comparisons for version numbers. Float numbers are rarely exact so 13.3 becomes 13.00000001 for example. The offset can be in either direction. Add an epsilon to your math, or use ints. – scosman May 26 '23 at 01:49
3

That says,

@available may only be used as condition of an 'if', 'guard' or 'while' statement

so, you can directly use that in if statements to check the availability instead of taking it into a variable.

if (@available(iOS 10, *)) {
  // PUT YOUR CODE HERE
} else {
}

In Swift 4.1

if #available(iOS 10.0, *) {

} else {

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bhavin Kansagara
  • 2,866
  • 1
  • 16
  • 20
3

A workaround can be:

BOOL isGoodIos = false;
if(@available(iOS 11, *)) { isGoodIos = true; }
....

BOOL shouldDoMagic = true;
if(shouldDoMagic && isGoodIos) {
    // TODO: magic
}
Stoica Mircea
  • 782
  • 10
  • 22