如何在Swift中取消特定警告 [英] How to suppress a specific warning in Swift

查看:872
本文介绍了如何在Swift中取消特定警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Swift函数,其功能如下:

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

由于 __ WORDSIZE 是常量,因此编译器始终给出开关体内至少有一个警告。实际标记的行取决于我要建立的目标(例如,iPhone 5 vs. 6;有趣的是,iPhone 5会针对64位情况发出警告,而iPhone 6会针对32位和默认情况给出两个警告)。

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).

我发现 #pragma 的Swift等效值为 // MARK:,所以我尝试了

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

但警告仍然存在, MARK 似乎没有任何作用。

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…?

推荐答案

目前(Xcode 7.1),似乎没有办法在Swift中取消特定警告(参见例如如何快速静音警告

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).

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

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

这两个32位编译器都没有警告和64位架构。

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

这篇关于如何在Swift中取消特定警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆