7

I have a Swift function doing something like this:

func f() -> Int {
    switch (__WORDSIZE) {
        case 32: return 1
        case 64: return 2
        default: return 0
    }
}

Because __WORDSIZE is a constant, the compiler always gives at least one warning in the switch body. Which lines are actually marked depends on the target I am building for (e.g. iPhone 5 vs. 6; interestingly iPhone 5 gives a warning for the 64-bit case whereas iPhone 6 gives two warnings for 32-bit and default).

I found out that the Swift equivalent for #pragma is // MARK:, so I tried

// MARK: clang diagnostic push
// MARK: clang diagnostic ignored "-Wall"
func f() -> Int {
    switch (__WORDSIZE) {
        case 32: return 1
        case 64: return 2
        default: return 0
    }
}
// MARK: clang diagnostic pop

but the warnings remain, the MARKs seem to have no effect.

As a workaround, I now have something like this:

#if arch(arm) || arch(i386)
    return 1
#else
    #if arch(arm64) || arch(x86_64)
        return 2
    #else
        return 0
    #endif
#endif

– but of course this is not the same. Any hints…?

Stefan
  • 1,036
  • 10
  • 32
  • 1
    At present, you cannot suppress specific warnings in Swift code (see e.g. http://stackoverflow.com/questions/31540446/how-to-silence-a-warning-in-swift-2-0). As a workaround, you can switch on `sizeof(Int.self)` instead (which is 4 or 8). – It would be interesting to know *why* you need this function. – Martin R Nov 04 '15 at 07:54
  • Thank you, your solution works. For the code, see here: http://stackoverflow.com/questions/24007129/how-does-one-generate-a-random-number-in-apples-swift-language — answer by jstn. – Stefan Nov 04 '15 at 08:30
  • 1
    I hadn't seen that before, but here http://stackoverflow.com/a/31429991/1187415 is a (quite similar) solution which does not need the switch on the word size. – Martin R Nov 04 '15 at 08:37
  • fwiw `switch nil ?? x` silences the "Switch condition evaluates to a constant" warning. the warning is annoying because, every build, it focuses the issue navigator tab. – danneu Apr 07 '23 at 04:06

1 Answers1

6

At present (Xcode 7.1), there seems to be no way of suppressing a specific warning in Swift (see e.g. How to silence a warning in swift).

In your special case, you can fool the compiler by computing the number of bytes in a word:

func f() -> Int {
    switch (__WORDSIZE / CHAR_BIT) { // Or: switch (sizeof(Int.self))
    case 4: return 1
    case 8: return 2
    default: return 0
    }
}

This compiles without warnings on both 32-bit and 64-bit architectures.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382