You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Sourcery如何修复Program类型自动继承Body协议的代码生成问题

问题原因

你的Sourcery模板存在3处核心错误导致无法生成预期的ArrayInterpretable遵从实现:

  1. 协议遵循判断的语法错误:在Stencil模板语法中,不能在if的变量表达式内嵌套{{}}占位符,你的type.Body.based.{{proto.name}}写法完全无法被模板引擎解析,条件永远为假。
  2. 没有过滤目标协议:你遍历了所有公共协议,没有限制只处理继承自Interpretation的协议,即使条件判断修复也会引入多余的协议实现。
  3. 无参数方法的生成代码缺失括号:方法定义没有加(),即使生成也会存在语法错误。

修复后的模板

{% 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:54:04