如何从此枚举中获取CustomStringConvertible描述?

时间:2017-10-11 15:48:51

标签: swift enums

我有以下枚举

enum Properties: CustomStringConvertible {
    case binaryOperation(BinaryOperationProperties),
    brackets(BracketsProperties),
    chemicalElement(ChemicalElementProperties),
    differential(DifferentialProperties),
    function(FunctionProperties),
    number(NumberProperties),
    particle(ParticleProperties),
    relation(RelationProperties),
    stateSymbol(StateSymbolProperties),
    symbol(SymbolProperties)
}

并且结构都看起来像这样

struct BinaryOperationProperties: Decodable, CustomStringConvertible {
    let operation: String
    var description: String { return operation }
}

那么如何使该枚举符合CustomStringConvertible?我尝试使用一个简单的getter,但显然是调用自己,而我想调用特定的struct。

奖励积分:定义的枚举是否具有名称?

1 个答案:

答案 0 :(得分:5)

这样的枚举称为枚举,具有关联值

我通过手动切换案例来实施description

extension Properties: CustomStringConvertible {
    var description: String {
        switch self {
        case .binaryOperation(let props):
            return "binaryOperation(\(props))"
        case .brackets(let props):
            return "brackets(\(props))"
        ...
        }
    }
}

编辑:另一种方法是使用Swift的Mirror反射API。实例的枚举案例被列为镜像的子项,您可以打印其标签和值,如下所示:

extension Properties: CustomStringConvertible {
    var description: String {
        let mirror = Mirror(reflecting: self)
        var result = ""
        for child in mirror.children {
            if let label = child.label {
                result += "\(label): \(child.value)"
            } else {
                result += "\(child.value)"
            }
        }
        return result
    }
}

(这是一个通用的解决方案,应该可用于许多类型,而不仅仅是枚举。您可能需要为具有多个子类的类型添加一些换行符。)

编辑2:Mirror也是printString(describing:)用于不符合Custom[Debug]StringConvertible的类型的内容。 You can check out the source code here