代码之家  ›  专栏  ›  技术社区  ›  Avba

swift-如何定义特定类型的间接枚举事例

  •  0
  • Avba  · 技术社区  · 6 年前

    我想定义一个 enum 表示的简化版本 markdown 文件

    我想要类似下面的内容,但不理解定义间接枚举的语法

    enum Markdown {
    case text(String)
    case sourceCode(code: String, language: Language)
    indirect case tableCell(either "text" or "sourceCode")
    indirect case tableRow(only table cells allowed)
    indirect case table(only tableRow allowed)
    }
    
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   clemens    6 年前

    由于 documentation 间接枚举只能引用自身。更细的粒度是不可能的。你的声明应该是这样的

    enum Markdown {
        case text(String)
        case sourceCode(code: String, language: String)
        indirect case tableCell(Markdown)
        indirect case tableRow([Markdown])
        indirect case table([Markdown])
    }
    
    let t = Markdown.text("Hello")
    let c = Markdown.tableCell(t)
    

    你也可以把 indirect 枚举声明前面的关键字,以避免重复:

    indirect enum Markdown {
        case text(String)
        case sourceCode(code: String, language: String)
        case tableCell(Markdown)
        case tableRow([Markdown])
        case table([Markdown])
    }
    

    您可以定义更多类型安全枚举:

    indirect enum Content {
        case text(String)
        case bold(Content)
        case italic(Content)
        case span([Content])
    }
    indirect enum TableRow {
        case tableCells([Content])
    }
    

    等。

    但我认为这会很快导致其他问题,您应该更愿意使用结构或类。