Search code examples
swiftxcodeios-simulatorcompiler-warnings

if targetEnvironment(simulator) Code after 'return' will never be executed


I get the Xcode warning: "Code after 'return' will never be executed", when I use this:

#if targetEnvironment(simulator)
    return
#endif

//Stuff that a simulator is unable to do

I use this in my code whenever a simulator truly can't do something, like scanning for NFC-codes. The easy solution would be to use an #else, but I don't like to put code within an #else only because Xcode doesn't realize the code will run when it's not a simulator. But perhaps a better argument, when I use the #else, all the code within the #else is greyed out by Xcode.

Is there a way to make Xcode realize that the code can be executed? Or suppress this warning somehow (without suppressing all warnings within this file)?


Solution

  • You make Xcode realize that the code can be executed by using #else. As you say, it's the easy solution. It's also the correct solution.

    You state:

    I don't like to put code within an #else only because Xcode doesn't realize the code will run when it's not a simulator.

    This is not true. Xcode does realize. That's the whole point of what it is doing. Either the code above the #else or the code below the #else will be grayed out depending on your current build target. Select a real device and the return will be grayed out indicating that it won't be used. Select a simulator and the other code will be grayed out indicating that it won't be used.

    In other words, Xcode grays out the code it knows will not currently be used based on the selected build target. You want this behavior so you know which code is currently active. It avoids any confusion about which code you are currently building and running.


    Having said all of that, Xcode does provide a setting that allows you to disable this feature. Bring up Xcode Settings and go to the Text Editing tab. Enable or disable the "Dim inactive code" option depending on whether you want Xcode to gray out the relevant code or not.