阅读体验更佳,请点击
先来看看效果:
优化前:
优化后:
第一步:认识Sourcery
Sourcery is a code generator for Swift language, built on top of Apple's own SourceKit. It extends the language abstractions to allow you to generate boilerplate code automatically.
Sourcery是一个Swift的代码生成器,基于Apple自家的SourceKit。它通过扩展语言的抽象性,来实现了自动生成模板代码。
第二步:书写模板
在项目中创建识别的标记:
第三步:Podfile中引入Sourcery
- pod 'Sourcery'
- pod install
第四步: add Script
在项目的Build Phases增加一个Script,命名为Sourcery。
$PODS_ROOT/Sourcery/bin/sourcery --sources $SRCROOT/creams --templates $SRCROOT/creams/Infrastructure/Sourcery/AutoUnbox/AutoUnbox.stencil --output $SRCROOT/creams/Infrastructure/Sourcery/
注意请将Sourcery放置在第一位,保证在代码编译之前,模板代码已经生成完毕
测试
- comand + B
- 在$SRCROOT/creams/Infrastructure/Sourcery/路径下会c生成一个AutoUnbox.generated.swift,这个文件中包含了所有生成的代码,即所有需要实现Unboxable的Model的Extension。