How to Suppress "Will never be executed" when testing C macros?

Swift will import C macros, so

#define IS_HIGH_RES (MAX_RESOLUTION > 1024)

becomes

let IS_HIGH_RES = true

but then testing it results in a warning:

if IS_HIGH_RES {
    .... 
} else {
    ....  ⚠️ Will never be executed
}

I tried the usual clang trick of surrounding the condition's expression with extra parentheses but that doesn't work.

Is there any way to silence this? (Haven't found one with lots of searching.) I'm trying to figure out how to get my Swift code to reasonably use my numerous C defines in this mixed codebase.

1 Like

In this example all values are known at compile time. Swift guarantees comparisons of IS_HIGH_RES and false will never be executed, which is why you get that warning.

There are many ways you can avoid the warning for this example. A few solutions:

  • removing the else block
  • manually making IS_HIGH_RES mutable (which brings a lot more complexity to the code, notably Swift's Sendability)
  • manually writing compiler directives declaring different values for IS_HIGH_RES

To my knowledge there is no easy way to suppress individual Swift compiler warnings, but you can use certain compiler flags to suppress all warnings (-suppress-warnings).

SE-0443 introduced more control over warning suppression which is only available starting with Swift 6.1, which hasn't been released yet.

It is worth noting that this compiler diagnostic should be respected as a warning because the compiler determined the block will never be executed based on the context, which may be unintended behavior. However, it can be ignored if you know what you're doing.

An explicit cast to Bool will suppress the warning:

if Bool(IS_HIGH_RES) {
  ... 
} else {
  ...
}
3 Likes

Mega. Exactly what I was looking for. Thanks @grynspan!

1 Like