stencilproject/Stencil

Output enum value

dmholmes opened this issue · 4 comments

Is there a way to get enum output in a template? I believe the key value coding doesn't work with enums in Swift resulting in empty output.

@dmholmes what exactly do you mean? have an example of input, template and expected output?

{{ lab.labType }}

Template would not output value for enums like this:

enum LabType: String {
    case creatinine = "Serum Creatinine"
    case alanineAminotransferase = "ALT"
    case aspartateAminotransferase = "AST"
    case bilirubin = "Total Bilirubin"
}

I was able to workaround by implementing CustomStringConvertible.

enum LabType: String, Codable, CustomStringConvertible {
    case creatinine = "Serum Creatinine"
    case alanineAminotransferase = "ALT"
    case aspartateAminotransferase = "AST"
    case bilirubin = "Total Bilirubin"
    
    var description: String {
        switch self {
        case .creatinine:
            return LabType.creatinine.rawValue
        case .alanineAminotransferase:
            return LabType.alanineAminotransferase.rawValue
        case .aspartateAminotransferase:
            return LabType.aspartateAminotransferase.rawValue
        case .bilirubin:
            return LabType.bilirubin.rawValue
        }
    }
}

When you are accessing Swift type properties Mirror can only access stored variables, not computed. rawValue of enums is also not accessible through Mirror

Yes, and very unfortunate in our Stencil use as we have quite a few enum.rawValue and computed properties. CustomStringConvertible for enums and didSet {} for objects are required for me to use Stencil.