Skip to content

Instantly share code, notes, and snippets.

@DJBen
Last active December 14, 2020 23:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DJBen/8ad1c7507cf1c717bca356b425cbdf7d to your computer and use it in GitHub Desktop.
Save DJBen/8ad1c7507cf1c717bca356b425cbdf7d to your computer and use it in GitHub Desktop.
Sourcery: Initializer stencil with default values
{# A template to generate initializer inline #}
{# Example: $sourcery --sources <path/to/source.swift> --templates <path/to/this/stencil> --output Output/ #}
{% for type in types.structs %}
{% set spacing %}{% if type.parentName %} {% endif %}{% endset %}
{% map type.storedVariables into parameters using var %}{{ var.name }}: {{ var.typeName }}{% if var.defaultValue %} = {{var.defaultValue}}{% elif var.typeName.isOptional %} = nil{% endif %}{% endmap %}
// sourcery:inline:auto:{{ type.name }}.AutoInit
{{spacing}} {{ type.accessLevel }} init({{ parameters|join:", " }}) {
{{spacing}} {% for variable in type.storedVariables %}
{{spacing}} self.{{ variable.name }} = {{ variable.name }}
{{spacing}} {% endfor %}
{{spacing}} }
// sourcery:end
{% endfor %}
@DJBen
Copy link
Author

DJBen commented Oct 21, 2019

See Sourcery page for user guide

@ferologics
Copy link

There is a bug in this template that causes it to generate random inits for all structs.
For anyone trying to use this add on line 4: {% if type|annotated:"AutoInit" %}
and then annotate any struct you want to autogenerate inits for with // sourcery: AutoInit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment