SourceryTemplates
Some templates to use for Code Generation in Swift with http://github.com/krzysztofzablocki/Sourcery
SourceryTemplates: Swift code generation, one template at a time
A set of Sourcery templates for Swift code generation, covering type erasure, interface protocols, property protocols, and enum case names. A demo Xcode project shows each one running.
Templates with a demo project attached
The templates live in the Templates directory and are meant to be used with Sourcery for Swift code generation. The TemplatesDemo Xcode project demonstrates them in action, with a unit test target holding use case examples for each template and code that exercises the generated output. Four entries are called out: AutoInterface, AutoPropertiesProtocol, AutoCaseName, and a pointer to other templates elsewhere.
AutoInterface and type erasure
AutoInterface generates a protocol that matches an API. To opt in, a type conforms to an empty phantom protocol, and the generated protocol picks up all the functions and properties of the type. The default name mirrors the type with an I prefix, so a WebService becomes an IWebService, and annotations can override the prefix, add a suffix, or force an exact name. A separate TypeErase template handles erasing associated types, and the README points at a BigNerdRanch article and a Try! Swift talk as the inspiration for it.
One protocol per property
AutoPropertiesProtocol generates a separate protocol for each property of a type, with that protocol exposing just the one property. The payoff is protocol composition for dependency injection: a single struct can hold all the dependencies while each generated protocol says exactly which piece a caller may touch. The default prefix is Has, and annotations can change the prefix or suffix, or name a protocol exactly.
Names, not payloads
AutoCaseName generates an extension that exposes the root name of a case in an enum that carries associated values. That lets code test for a case with a simple if or guard, which a plain guard cannot do with pattern matching. The generated CaseName enum is Comparable, so two instances can be compared by case regardless of payload, and it is RawRepresentable with a String, so rawValue returns the case name as text.
Editorial conclusion
Each template follows the same rhythm: declare a phantom protocol, conform a type to it, run Sourcery. The author admits the templates have not seen heavy real-world use, so corner cases may be missing.
Community notes