zaitsman
zaitsman

Reputation: 9499

Map properties to another object in Swift

let's say I have a struct like so

struct MyStruct: Codable {
  var bool1: Bool? = false
  var bool2: Bool
  var whateverElse: Date
  var andThis: String?
}

Now that struct has some 30 properties and from time to time I need to add more of them.

In part of the logic of the app, I need to reset only boolean properties from another instance of the same struct, so I have a boring method like so:

func resetToValues(_ from: MyStruct) {
  self.bool1 = from.bool1
  self.bool2 = from.bool2
}

Note that whateverElse and andThis are not reset. Every time I add a property, I have to add a line to this method which is annoying.

Is there some way to automate it such that only Bool and Bool? properties are reset?

I thought of getting at CodingKeys and iterating over them, but unfortunately since I can't get a lot out of Mirror.Child nor get a KeyPath by string I am stuck in that I can't determine what is Bool and what is not.

Upvotes: 0

Views: 279

Answers (1)

nghiahoang
nghiahoang

Reputation: 568

you can use sorcery to generate code: https://github.com/krzysztofzablocki/Sourcery

  1. Install Sourcery
  2. Add template.stencil file:

The template file for you could be:

import Foundation

{% for type in types %}
extension {{type.name}} {
    mutating func reset(with other: {{type.name}}) {
        {% for variable in type.storedVariables %}
        {% if variable.typeName|hasPrefix:"Bool" %}
        self.{{variable}} = other.{{variable}}
        {% endif %}
        {% endfor %}
    }
}
{% endfor %}
  1. Add new script to build phase:

    sourcery --sources <path.to.your.struct> --templates <path.to.stencil> --output <path.to.output>

  2. Build and add output file to your project (only for the first time)

Upvotes: 2

Related Questions