Swift Sourcery如何修复Program类型自动继承Body协议的代码生成问题
问题原因
你的Sourcery模板存在3处核心错误导致无法生成预期的ArrayInterpretable遵从实现:
- 协议遵循判断的语法错误:在Stencil模板语法中,不能在
if的变量表达式内嵌套{{}}占位符,你的type.Body.based.{{proto.name}}写法完全无法被模板引擎解析,条件永远为假。 - 没有过滤目标协议:你遍历了所有公共协议,没有限制只处理继承自
Interpretation的协议,即使条件判断修复也会引入多余的协议实现。 - 无参数方法的生成代码缺失括号:方法定义没有加
(),即使生成也会存在语法错误。
修复后的模板
{% for type in types.based.Program|public %} extension {{type.name}} : Interpretation {} // 仅遍历继承自Interpretation的公共协议 {% for proto in types.protocols|public where proto.based.Interpretation %} // 正确用下标访问判断Body是否遵循当前协议 {% if type.Body.based[proto.name] %} extension {{type.name}} : {{proto.name}} { {% for variable in proto.variables|instance %} @inlinable public var {{variable.name}} : {{variable.typeName}} { body.{{variable.name}} } {% endfor %} {% for method in proto.methods|instance where method.parameters.count == 0 %} @inlinable public func {{method.name}}() -> {{method.returnTypeName}} { body.{{method.name}}() } {% endfor %} } {% endif %} {% endfor %} {% endfor %}
模板额外新增了method.parameters.count == 0的过滤规则,刚好匹配你要求的仅适配无入参实例方法的限制。
预期补充生成代码
修复模板后会额外生成以下符合要求的代码:
extension Bar : ArrayInterpretable { @inlinable public var asArray : Array<T> { body.asArray } }
内容的提问来源于stack exchange,提问作者MKasperczyk
相关产品推荐
相关产品推荐

