我想定义一个 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)
}
最佳答案
由于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])
}
等等
但我认为这很快会导致其他问题,您应该使用结构或类。
关于swift - 如何定义特定类型的间接枚举情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509582/