Home > Software engineering >  Xcode preprocessor, variables and "Will never be executed"
Xcode preprocessor, variables and "Will never be executed"

Time:03-25

In a Swift based project, I need to set the value of a variable according to a preprocessor rule, like in the example below.

var doSomething = false
#if targetEnvironment(macCatalyst)
doSomething = true
#endif

if doSomething {
    print("Execute!")
}

If I build the code for an iOS simulator, Xcode will generate a "Will never be executed" warning at the print("Execute!") line. This make sense because preprocessor rules are evaluated before compilation and therefore the code above, when the target is an iOS simulator, corresponds to:

var doSomething = false

if doSomething {
    print("Execute!")
}

I just want to know if there is any advices for handling cases like that. Ideally, I would like to avoid using the preprocessor condition for every statement, like so:

#if targetEnvironment(macCatalyst)
print("Execute!")
#endif

but rely on a variable like the original example. I would also prefer to avoid completely disabling in Xcode the display of "Will never be executed" warnings for all source codes.

Is there a way to set the "doSomething" variable so that Xcode doesn't display the warning in a case like that?

Thank you


Update:

Thanks to Swinny89 for suggesting using a lazy var. It works great! Below you can find the final code:

lazy var doSomething: Bool = {
   #if targetEnvironment(macCatalyst)
      return true
   #else
      return false
   #endif
}()

if doSomething {
    print("Execute!")
}

CodePudding user response:

For readability and ease of use I would use a lazy var set by a function. This means that we're not wasteful in redefining the same thing twice and that this function will only be run once in setting your value:

///Var is true if running on macCatalyst, otherwise false
lazy var doSomething = {
    #if targetEnvironment(macCatalyst)
        return true
    #else
        return false
    #endif
}()

if doSomething {
    print("Execute!")
}
  • Related