Diggory
(Diggory)
1
<The title of this post was renamed from " Is this a bug? return statement inside #if os() causes warning " to be more accurate>
Hello, the following code:
import Foundation
func testLinux() {
#if !os(Linux)
print("Bailing - not on Linux, this function is not relevant")
return
#endif
// OK, we're on Linux.
print("We are on Linux")
}
gives an error:
Code after 'return' will never be executed
Is this a bug? Or should I create a variable which is flipped inside the #if statement and then return later based on that? (edit - even if I do that, the warning is still present.)
Jumhyn
(Frederick Kellison-Linn)
2
The correct tool here is to do:
#if !os(Linux)
print("Bailing - not on Linux, this function is not relevant")
#else
print("We are on Linux")
#endif
In your example, since all of the diagnostic logic happens after the conditional compilation determines what AST is built, you basically end up with the same AST as if you wrote:
print("Bailing - not on Linux, this function is not relevant")
return
print("We are on Linux")
BigZaphod
(Sean Heber)
3
You could do this, maybe:
func testLinux() {
#if !os(Linux)
print("Bailing - not on Linux, this function is not relevant")
#else
print("We are on Linux")
#endif
}
Diggory
(Diggory)
4
Thanks - I suppose I was confusing the pre-processor with runtime evaluation.
I was looking for a way to exit the function early depending on platform. I imagine I should instead use an equivalent to the old Classic macOS 'Gestalt'.
Maybe: Apple Developer Documentation
Thanks again. A category error on my part....
Diggory
(Diggory)
5
ProcessInfo reports OS version but that's not very useful.
e.g.
Linux:
OperatingSystemVersion(majorVersion: 4, minorVersion: 19, patchVersion: 0)
macOS Mojave:
"NSOperatingSystemVersion(majorVersion: 10, minorVersion: 14, patchVersion: 6)\n"
I suppose one could use #if canImport(xxx) or assume that we're not using macOS version 4.0.....
Perhaps ProcessInfo.platform() would be a useful method to add.