-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathAutocopy.stencil
63 lines (52 loc) · 1.91 KB
/
Autocopy.stencil
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{# Thanks to: https://arasthel.com/data-classes-on-swift/#selectwhichvalueswillbechangedandwhichwillbecopied #}
// swiftlint:disable all
public protocol AutoCopy { }
public extension AutoCopy {
func setValueOptional<T>(_ value: OptionalCopyValue<T>, _ defaultValue: T?) -> T? {
switch(value) {
case let .new(content):
return content
case .same:
return defaultValue
default:
return nil
}
}
}
public enum OptionalCopyValue<T>: ExpressibleByNilLiteral {
case new(T)
case same
case `nil`
public init(nilLiteral: ()) {
self = .nil
}
}
prefix operator *
prefix func * <T>(lhs: T) -> OptionalCopyValue<T> {
return .new(lhs)
}
// swiftlint:enable all
{# Thanks to: https://arasthel.com/data-classes-on-swift/#selectwhichvalueswillbechangedandwhichwillbecopied #}
{% for type in types.all where type.implements.AutoCopy %}
{% if type|annotated:"import" %}
{% for import in type.annotations.import|toArray %}
import {{ import }}
{% endfor %}
{% endif %}
// swiftlint:disable all
extension {{ type.name }} {
func copy(
{% for variable in type.storedVariables %}
{{ variable.name }} copied_{{ variable.name }}: OptionalCopyValue<{{ variable.unwrappedTypeName }}> = .same{% if not forloop.last %}, {% endif %}
{% endfor %}
) -> {{ type.name }} {
return {{ type.name }}(
{% for variable in type.storedVariables %}
{% if variable.isOptional %}
{{ variable.name }}: setValueOptional(copied_{{ variable.name }}, self.{{ variable.name }}){% else %}{{ variable.name }}: setValueOptional(copied_{{ variable.name }}, self.{{ variable.name }}) ?? self.{{ variable.name }}{% endif %}{% if not forloop.last %}, {% endif %}
{% endfor %}
)
}
}
{% endfor %}
// swiftlint:enable all