Preprocessor, variables and "Will never be executed"

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" alert 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

Answered by DaleOne in 708324022

Someone on Stack Overflow advised me to use a lazy var. It works great!

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

if doSomething {
    print("Execute!")
}
Accepted Answer

Someone on Stack Overflow advised me to use a lazy var. It works great!

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

if doSomething {
    print("Execute!")
}
Preprocessor, variables and "Will never be executed"
 
 
Q