Skip to content

Instantly share code, notes, and snippets.

@onevcat
Created March 12, 2018 04:54
Show Gist options
  • Save onevcat/ace60350f1c9c8a189f2788bc5ae2750 to your computer and use it in GitHub Desktop.
Save onevcat/ace60350f1c9c8a189f2788bc5ae2750 to your computer and use it in GitHub Desktop.
dictionary.stencil
{# 找到所有实现了 DictionaryConvertible 的类型 #}
{% for t in types.implementing.DictionaryConvertible %}
{# 为该类型 t 创建 extension #}
extension {{ t.name }} {
var value: [String: Any] {
return [
{# 对类型中的所有存储属性迭代 #}
{% for val in t.storedVariables %}
{% if val.isArray %} {# 如果变量是数组,map 其中的值进行嵌套 #}
"{{val.name}}": {{val.name}}.map { $0.value }
{% elif val.isDictionary %} {# 如果变量是数组,mapValues 字典值进行嵌套 #}
"{{val.name}}": {{val.name}}.mapValues { $0.value }
{% else %} {# 非容器类型,如果是其他的 DictionaryConvertible,则调用 value, 否则直接使用变量即可 #}
"{{val.name}}": {% if val.type.implements.DictionaryConvertible %}{{val.name}}.value{% else %}{{val.name}}{% endif %}
{% endif%}
{% if not forloop.last %},{% endif %} {# 为了语法正确 #}
{% endfor %}
]
}
}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment