stencilproject / Stencil

Stencil is a simple and powerful template language for Swift.
https://stencil.fuller.li
BSD 2-Clause "Simplified" License
2.34k stars 224 forks source link

Output enum value #237

Closed dmholmes closed 6 years ago

dmholmes commented 6 years ago

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.

ilyapuchka commented 6 years ago

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

dmholmes commented 6 years ago

{{ 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
        }
    }
}
ilyapuchka commented 6 years ago

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

dmholmes commented 6 years ago

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.