Skip to content

Instantly share code, notes, and snippets.

@adurbalo
Created June 4, 2020 08:10
Show Gist options
  • Save adurbalo/b210d806b8b6ed1e385b26d7d6178c9d to your computer and use it in GitHub Desktop.
Save adurbalo/b210d806b8b6ed1e385b26d7d6178c9d to your computer and use it in GitHub Desktop.
Sourcery template that extends AutoInit by setting default values as nil to optional's fields
{% for type in types.structs %}
{% if type|annotated:"AutoInitDefaultValues" or type.implements.AutoInitDefaultValues %}
{% 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 }}.AutoInitDefaultValues
{{spacing}} {{ type.accessLevel }} init({{ parameters|join:", " }}) { // swiftlint:disable:this line_length
{{spacing}} {% for variable in type.storedVariables %}
{{spacing}} self.{{ variable.name }} = {{ variable.name }}
{{spacing}} {% endfor %}
{{spacing}} }
// sourcery:end
{% endif %}
{% endfor %}
@adurbalo
Copy link
Author

adurbalo commented Jun 4, 2020

Usage

  • Define empty protocol
    protocol AutoInitDefaultValues {}
  • Then confirm it to target structs
    extension <SOME_STRUCT_NAME>: AutoInitDefaultValues {}
  • Build ⌘B or Run ⌘R and have a fun

Sourcery config required, more details in documentation

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