3

I find myself spending a lot of time writing boilerplate constructors code like the following. Is there a way to make XCode generate this/some way to make this process faster?

public class T {
  let t1: T1
  let t2: T2
  let t3: T3

  public init(t1: T1, t2: T2, t3: T3) {
    self.t1 = t1
    self.t2 = t2
    self.t3 = t3
  } 
user1615898
  • 1,185
  • 1
  • 10
  • 20
  • 3
    If appropriate, use a `struct` instead of a `class` and such an `init` method is provided by default. – rmaddy Mar 14 '17 at 16:23
  • 1
    Found this github repo, may it helps. Sorry for giving link only :) https://github.com/rjoudrey/swift-init-generator – Tony Nguyen Mar 14 '17 at 16:42
  • It works out of the box without any additional repo's with my answer here: https://stackoverflow.com/a/54378722/7715250 – J. Doe Jan 26 '19 at 13:17

1 Answers1

2

Sourcery is the great tool for that.

Here is template you can use (for sourcery version > 0.10):

{% for type in types.structs %}
{% if type|annotated:"AutoInit" %}
{% set spacing %}{% if type.parentName %}    {% endif %}{% endset %}
{% map type.storedVariables into parameters using var %}{{ var.name }}: {{ var.typeName }}{% endmap %}
// sourcery:inline:auto:{{ type.name }}.AutoInit
{{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 %}

I got template from this AutoInit article

DavidB.
  • 99
  • 1
  • 4