Last active
December 14, 2020 23:36
-
-
Save DJBen/8ad1c7507cf1c717bca356b425cbdf7d to your computer and use it in GitHub Desktop.
Sourcery: Initializer stencil with default values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# 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 %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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