在Swift中将属性映射到另一个对象

时间:2020-06-25 06:32:31

标签: swift

假设我有一个像这样的结构

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

现在该结构具有约30个属性,我不时需要添加更多这些属性。

在应用程序逻辑中,我需要从同一结构的另一个实例中重置 only boolean 属性,所以我有一个无聊的方法,如下所示:

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

请注意,whateverElseandThis不会重置。 每次添加属性时,都必须为此方法添加一行,这很烦人。

是否有某种方法可以使它自动重置为BoolBool?属性?

我本来想去CodingKeys并对其进行迭代,但是不幸的是,由于我不能从Mirror.Child中获益良多,也无法通过字符串得到KeyPath,因此我陷入了困境我无法确定什么是布尔,什么不是。

1 个答案:

答案 0 :(得分:2)

您可以使用魔术来生成代码: https://github.com/krzysztofzablocki/Sourcery

  1. 安装Sourcery
  2. 添加template.stencil文件:

您的模板文件可以是:

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. 添加新脚本以建立阶段:

    sourcery --sources --templates --output

  2. 构建输出文件并将其添加到您的项目中(仅第一次)