Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Code Generation in Swift: Live Demo — NSBudapest 04.2017

Code Generation in Swift: Live Demo — NSBudapest 04.2017

Slides used in my talk at the NSBudapest meetup in April'17

The talk was mainly a live demo to demonstrate both SwiftGen and Sourcery, the most popular tools to do Code Generation in Swift.

- you can find the video here: http://www.ustream.tv/recorded/103135632
- the sample code used for the live demo here: https://github.com/AliSoftware/CodeGenDemo

---

Swift is a great, type safe and powerful language. But some stuff are still cumbersome to write yourself. And some APIs could deserve more type-safety and less string-based methods.

In this talk we'll discover some popular tools to do code generation for Swift, especially Sourcery and SwiftGen. We'll see how they work, what you can do with them, some concrete and advanced examples of how your code can be made safer, and how you can save a lot of development time thanks to those tools.

AliSoftware

April 26, 2017
Tweet

More Decks by AliSoftware

Other Decks in Programming

Transcript

  1. Code Generation Principles Parser Internal Representation Stencil Template Generated Code

    Template Engine Input Resource
 Assets Catalog Fonts Storyboards …
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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