Skip to content

Guidelines for Writing View Models

Travis Prescott edited this page Jul 24, 2020 · 1 revision

Autorest.Swift renders code using the Stencil templating language. Because Swift's Mirror API does not work with computed properties, we have opted to create specific ViewModels that describe the contents of the Swift code, assembling and translating potentially numerous code model concepts into a cohesive ViewModel that describes a specific Swift file.

Here are some guidelines when writing *.stencil files and corresponding ViewModels:

  1. Stencil files should use composition to reduce duplication and ease maintenance.

  2. Stencil files should use {% for ... %} loop syntax, but should avoid containing conditional logic as it makes the template hard to read and maintain. Compare:

Stencil with conditionality

public {{ model.objectType }} {{ model.name }} {
    {% for property in model.properties %}
    {% if property.comment %}
    /// {{ property.comment }}
    {% endif %}
    public let {{ property.name }}: {{ property.type }}{% if property.optional %}?{% endif %}{% if property.defaultValue %} = "{{property.defaultValue}}"{% endif %}
    {% endfor %}
}

Stencil without conditionality

{{ model.comment }}
public {{ model.objectType }} {{ model.name }} {
    {% for property in model.properties %}
    {{ property.comment }}
    public let {{ property.name }}: {{ property.type }}{{property.defaultValue}}
    {% endfor %}
}
  1. Create ViewModelPrimitive structs (ex: ViewModelComment) to handle conditional logic. These are initialized from one or more code model properties and will store the appropriate string representation in a description field that fulfills the CustomStringConvertible protocol. This allows you to simply reference the property in the template ({{ model.prop }}) as though it were a string instead of a struct ({{ model.prop.description }}).