swift 中的条件编译案例语句

Conditionally-compiled case statement in swift

我在 Swift 中实现了一个带有计算属性的枚举语句。我想添加有条件编译的值,例如仅适用于某些配置。

这是我正在尝试做的一个例子:

enum Rows: Int
{
    case Row1
    case Row2
    #if DEBUG
    case Debug
    #endif

    var rowTitle: String
    {
        case Row1: return "Row 1"
        case Row2: return "Row 2"
        #if DEBUG
        case Debug: return "Debug"
        #endif
    }
}

这似乎不受支持,因为我在 switch 语句中的 case 语句中收到以下错误消息:

'case' label can only appear inside a 'switch' statement

在 Swift 中有没有办法做到这一点?

谢谢,
大卫

你的条件编译语法看起来是正确的。但是,当我将您的代码粘贴到操场上时,出现多个错误。第一个是var rowTitle开头的行,错误是"Enums may not contain stored properties".

这是您的代码版本,在语法上对于计算变量的实现是正确的 rowTitle:

enum Rows: Int
{
    case Row1
    case Row2

    var rowTitle: String {
            switch self {
            case Row1:
                return "Row 1"
            case Row2:
                return "Row 2"
        }
    }
}

说的,这可能是你在问题中的意思......但不起作用:

enum Rows: Int
{
    case Row1
    case Row2
    #if DEBUG
    case Debug
    #endif

    var rowTitle: String {
        switch self {
        case Row1:
            return "Row 1"
        case Row2:
            return "Row 2"
        }
        #if DEBUG
            switch self {
            case Debug:
            return "Debug"
            default:
            break
            }
        #endif
    }
}

编译器不会给你任何错误,但你将无法使用Debug大小写。

这是 Swift 中的 known bug。目前无法在开关内进行条件编译。

从 Swift 4.

开始,现在可以对枚举案例进行条件编译
enum Foo {
    case bar

    #if DEBUG
    case baz
    #endif
}

let bar = Foo.bar

#if DEBUG
let baz = Foo.baz
#endif