Slide 1

Slide 1 text

Code Generation in Swift SwiftGen & Sourcery ✨ @aligatr NSBudapest Apr 26, 2017 Olivier Halligon

Slide 2

Slide 2 text

Demo SwiftGen ✨

Slide 3

Slide 3 text

Code Generation Principles Parser Internal Representation Stencil Template Generated Code Template Engine Input Resource
 Assets Catalog Fonts Storyboards …

Slide 4

Slide 4 text

Code Generation Principles enum Assets: String { {% for image in images %} case {{image|swiftIdentifier|lowerFirstWord}} = "{{image}}" {% endfor %} var image: UIImage { return UIImage(asset: self) } } extension UIImage { convenience init!(asset: Assets) { self.init(named: asset.rawValue) } } { "images": [ "Apple", "Banana", "Orange", "Some-Pears" ] } Template Internal Representation

Slide 5

Slide 5 text

Code Generation Principles enum Assets: String { case apple = "Apple" case banana = "Banana" case orange = "Orange" case somePears = "Some-Pears" var image: UIImage { return Image(asset: self) } } extension UIImage { convenience init!(asset: Assets) { self.init(named: asset.rawValue) } } Generated Code Internal Representation Template Engine Template let img = UIImage(asset: .banana) Call site

Slide 6

Slide 6 text

Candidates • Asset Catalogs • Localizable.strings • Custom Fonts • Storyboard names • Storyboard scenes • Segues identifiers • … JSON? Plist?… Parser Internal Representation Template Engine Template Generated Code } images-swift2.stencil images-swift3.stencil strings-swift3.stencil strings-customized.stencil

Slide 7

Slide 7 text

MetaProgramming Parser Internal Representation Stencil Template Generated Code Template Engine Your code (SourceKitten)

Slide 8

Slide 8 text

Demo Sourcery

Slide 9

Slide 9 text

Going Further • Building an API Client using Sourcery Annotations • littlebitesofcocoa.com/295-building-an-api-client-with-sourcery-key-value-annotations • Generate JSON Parsing code • github.com/Liquidsoul/Sourcery-AutoJSONSerializable

Slide 10

Slide 10 text

Going Further • Krzysztof’s talk at CraftConf • « Type-safe meta programming in Swift? Lets talk about Sourcery » • Friday 4:35pm, Platform 2 • Improve SwiftGen • We love contrbutors! ❤ • A lot of very interesting ideas pending implementation

Slide 11

Slide 11 text

Hello, I’m Olivier github.com/SwiftGen/SwiftGen github.com/krzysztofzablocki/Sourcery github.com/AliSoftware (OHHTTPStubs, Reusable, …) alisoftware.github.io @aligatr ✨