Let's create an AutoCopy.stencil protocol, so that Article copy implementation can be generated using Sourcery:
{% for type in types.implementing.AutoCopy %}
extension {{ type.name }}: NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return {{type.name}}(
{% map type.variables into vars using var %}
{{ var.name }}: {{ var.name }}{% endmap %}
{{ vars|join:"," }})
}
}
{% endfor %}
It will generate the following AutoCopy.generated.swift:
extension Article: NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return Article(
id: id,
title: title,
contents: contents,
author: author,
date: date,
views: views)
}
}
As you may have noticed, this is a simple implementation where the array's contents are not copied through the NSCopying protocol. Recursively, all objects that are copied should be copied by calling the .copy() method, if available.