如何在Swift中抑制特定警告

时间:2015-11-04 07:41:55

标签: swift compiler-warnings

我有一个Swift函数做这样的事情:

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

因为__WORDSIZE是一个常量,所以编译器总是在switch体中给出至少一个警告。实际标记的是哪些行取决于我正在构建的目标(例如,iPhone 5对6;有趣的是iPhone 5给出了64位情况的警告,而iPhone 6给出了32位和默认的两个警告)。

我发现#pragma的Swift等价物是// MARK:,所以我试过了

// 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

但警告仍然存在,MARK似乎无效。

作为一种解决方法,我现在有这样的事情:

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

- 但当然这不一样。任何提示......?

1 个答案:

答案 0 :(得分:6)

目前(Xcode 7.1),似乎无法在Swift中抑制特定警告(参见例如How to silence a warning in swift)。

在您的特殊情况下,您可以欺骗编译器 计算单词中 bytes 的数量:

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

在32位和64位架构上编译时都没有警告。