Swiftpack.co - Package - SwiftGen/SwiftGen


CircleCI CocoaPods Compatible Platform

SwiftGen is a tool to auto-generate Swift code for resources of your projects, to make them type-safe to use.

SwiftGen Logo Then generate constants for:

There are multiple benefits in using this:

  • Avoid any typo you could have when using a String
  • Free auto-completion
  • Avoid the risk to use an non-existing asset name
  • All this will be ensured by the compiler.

Also, it's fully customizable thanks to Stencil templates, so even if it comes with predefined templates, you can make your own to generate whatever code fits your needs and your guidelines!


There are multiple possibilities to install SwiftGen on your machine or in your project, depending on your preferences and needs:

Download the ZIP for the latest release

We recommend that you unarchive the ZIP inside your project directory and commit its content to git. This way, all coworkers will use the same version of SwiftGen for this project.

If you unarchived the ZIP file in a folder e.g. called swiftgen at the root of your project directory, you can then invoke SwiftGen in your Script Build Phase using:

"$PROJECT_DIR"/swiftgen/bin/swiftgen …

Via CocoaPods

If you're using CocoaPods, simply add pod 'SwiftGen', '~> 6.0' to your Podfile.

Then execute pod install --repo-update (or pod update SwiftGen if you want to update an existing SwiftGen installation) to download and install the SwiftGen binaries and dependencies in Pods/SwiftGen/bin/swiftgen next to your project.

Given that you can specify an exact version for SwiftGen in your Podfile, this allows you to ensure all coworkers will use the same version of SwiftGen for this project.

You can then invoke SwiftGen in your Script Build Phase using:

$PODS_ROOT/SwiftGen/bin/swiftgen …

Similarly, be sure to use Pods/SwiftGen/bin/swiftgen instead of just swiftgen where we mention commands with swiftgen in the rest of the documentation.

Note: SwiftGen isn't really a pod, as it's not a library your code will depend on at runtime; so the installation via CocoaPods is just a trick that installs the SwiftGen binaries in the Pods/ folder, but you won't see any swift files in the Pods/SwiftGen group in your Xcode's Pods.xcodeproj. That's normal: the SwiftGen binary is still present in that folder in the Finder.

Via Homebrew (system-wide installation)

To install SwiftGen via Homebrew, simply use:

$ brew update
$ brew install swiftgen

This will install SwiftGen system-wide. The same version of SwiftGen will be used for all projects on that machine, and you should make sure all your coworkers have the same version of SwiftGen installed on their machine too.

You can then invoke swiftgen directly in your Script Build Phase (as it will be in your $PATH already):

swiftgen … 

Note: SwiftGen needs Xcode 8.3 to build, so installing via Homebrew requires you to have Xcode 8.3 installed (which in turn requires macOS 10.12). If you use an earlier version of macOS, you'll have to use one of the other installation methods instead.

Via Mint (system-wide installation)

❗️SwiftGen 6.0 or higher only.

To install SwiftGen via Mint, simply use:

$ brew install libxml2
$ mint install SwiftGen/SwiftGen

Compile from source (only recommended if you need features from master or want to test a PR)

This solution is when you want to build and install the latest version from master and have access to features which might not have been released yet.

  • If you have homebrew installed, you can use the following command to build and install the latest commit:
brew install swiftgen --HEAD
  • Alternatively, you can clone the repository and use rake cli:install to build the tool and install it from any branch, which could be useful to test SwiftGen in a fork or a Pull Request branch.

Some Ruby tools are used in the build process, and the system Ruby works well if you are running a recent macOS. However, if you are using rbenv you can run rbenv install to make sure you have a matching version of Ruby installed.

Then install the Ruby Gems:

# Install bundle if it isn't installed
gem install bundle
# Install the Ruby gems from Gemfile
bundle install

You can now install to the default locations (no parameter) or to custom locations:

# Binary is installed in `./build/swiftgen/bin`, frameworks in `./build/swiftgen/lib` and templates in `./build/swiftgen/templates`
$ rake cli:install
# - OR -
# Binary will be installed in `~/swiftgen/bin`, frameworks in `~/swiftgen/fmk` and templates in `~/swiftgen/tpl`
$ rake cli:install[~/swiftgen/bin,~/swiftgen/fmk,~/swiftgen/tpl]

You can then invoke SwiftGen using the path to the binary where you installed it:

~/swiftgen/bin/swiftgen …

Or add the path to the bin folder to your $PATH and invoke swiftgen directly.


❗️ If you're migrating from older SwiftGen versions, don't forget to read the Migration Guide.

SwiftGen is provided as a single command-line tool which uses a configuration file to run various actions (subcommands).

Each action described in the configuration file (strings, fonts, ib, …) typically corresponds to a type of input resources to parse (strings files, IB files, Font files, JSON files, …), allowing you to generate constants for each types of those input files.

To use SwiftGen, simply create a swiftgen.yml YAML file to list all the subcommands to invoke, and for each subcommand, the list of arguments to pass to it. For example:

  inputs: Resources/Base.lproj
  filter: .+\.strings$
    - templateName: structured-swift4
      output: Generated/strings.swift
    - Resources/Images.xcassets
    - Resources/MoreImages.xcassets
    - templateName: swift4
      output: Generated/assets-images.swift

Then you just have to invoke swiftgen config run, or even just swiftgen for short, and it will execute what's described in the configuration file

To learn more about the configuration file — its more detailed syntax and possibilities, how to pass custom parameters, using swiftgen config lint to validate it, how to use alternate config files, and other tips — see the dedicated documentation.

There are also additional subcommands you can invoke from the command line to manage and configure SwiftGen:

  • The swiftgen config subcommand to help you with the configuration file, especially swiftgen config lint to validate that your Config file is valid and has no errors
  • The swiftgen templates subcommands helps you print, duplicate, find and manage templates (both bundled and custom)

Lastly, you can use --help on swiftgen or one of its subcommand to see the detailed usage.

Directly invoking a subcommand

While we highly recommend the use a configuration file for performance reasons (especially if you have multiple outputs, but also because it's more flexible), it's also possible to directly invoke the available subcommands to parse various resource types:

  • swiftgen colors [OPTIONS] DIRORFILE1 …
  • swiftgen coredata [OPTIONS] DIRORFILE1 …
  • swiftgen fonts [OPTIONS] DIRORFILE1 …
  • swiftgen ib [OPTIONS] DIRORFILE1 …
  • swiftgen json [OPTIONS] DIRORFILE1 …
  • swiftgen plist [OPTIONS] DIRORFILE1 …
  • swiftgen strings [OPTIONS] DIRORFILE1 …
  • swiftgen xcassets [OPTIONS] DIRORFILE1 …
  • swiftgen yaml [OPTIONS] DIRORFILE1 …

One rare cases where this might be useful — as opposed to using a config file — is if you are working on a custom template and want to quickly test the specific subcommand you're working on at each iteration/version of your custom template, until you're happy with it.

Each subcommand generally accepts the same options and syntax, and they mirror the options and parameters from the configuration file:

  • --output FILE or -o FILE: set the file where to write the generated code. If omitted, the generated code will be printed on stdout.
  • --templateName NAME or -n NAME: define the Stencil template to use (by name, see here for more info) to generate the output.
  • --templatePath PATH or -p PATH: define the Stencil template to use, using a full path.
  • Note: you should specify one and only one template when invoking SwiftGen. You have to use either -t or -p but should not use both at the same time (it wouldn't make sense anyway and you'll get an error if you try)
  • --filter REGEX or -f REGEX: the filter to apply to each input path. Filters are applied to actual (relative) paths, not just the filename. Each command has a default filter that you can override with this option.
  • Note: use .+ to match multiple characters (at least one), and don't forget to escape the dot (\.) if you want to match a literal dot like for an extension. Add $ at the end to ensure the path ends with the extension you want. Regular expressions will be case sensitive by default, and not anchored to the start/end of a path. For example, use .+\.xib$ to match files with a .xib extension. Use a tool such as RegExr to ensure you're using a valid regular expression.
  • Each command supports multiple input files (or directories where applicable).
  • You can always use the --help flag to see what options a command accept, e.g. swiftgen xcassets --help.

Choosing your template

SwiftGen is based on templates (it uses Stencil as its template engine). This means that you can choose the template that fits the Swift version you're using — and also the one that best fits your preferences — to adapt the generated code to your own conventions and Swift version.

Bundled templates vs. Custom ones

SwiftGen comes bundled with some templates for each of the subcommand (colors, coredata, fonts, ib, json, plist, strings, xcassets, yaml), which will fit most needs. But you can also create your own templates if the bundled ones don't suit your coding conventions or needs. Simply either use the templateName output option to specify the name of the template to use, or store them somewhere else (like in your project repository) and use templatePath output option to specify a full path.

💡 You can use the swiftgen templates list command to list all the available templates (both custom and bundled templates) for each subcommand, list the template content and dupliate them to create your own.

For more information about how to create your own templates, see the dedicated documentation.

Templates bundled with SwiftGen:

As explained above, you can use swiftgen templates list to list all templates bundled with SwiftGen. For most SwiftGen subcommands, we provide, among others:

  • A swift3 template, compatible with Swift 3
  • A swift4 template, compatible with Swift 4
  • Other variants, like flat-swift3/4 and structured-swift3/4 templates for Strings, etc.

You can find the documentation for each bundled template here in the repo, with documentation organized as one folder per SwiftGen subcommand, then one MarkDown file per template.
Each MarkDown file documents the Swift Version it's aimed for, the use case for that template (in which cases you might favor that template over others), the available parameters to customize it on invocation (using the params: key in your config file), and some code examples.

Don't hesitate to make PRs to share your improvements suggestions on the bundled templates 😉

Additional documentation


The SwiftGen.playground available in this repository will allow you to play with the code that the tool typically generates, and see some examples of how you can take advantage of it.

This allows you to have a quick look at how typical code generated by SwiftGen looks like, and how you will then use the generated constants in your code.

Dedicated Documentation in Markdown

There is a lot of documentation in the form of Markdown files in this repository, and in the related StencilSwiftKit repository as well.

Be sure to check the "Documentation" folder of each repository.

Especially, in addition to the previously mentioned Migration Guide and Configuration File documentation, the Documentation/ folder in the SwiftGen repository also includes:


You can also find other help & tutorial material on the internet, like this classroom about Code Generation I gave at FrenchKit in Sept'17 — and its wiki detailing a step-by-step tutorial about installing and using SwiftGen (and Sourcery too)

Asset Catalog

  inputs: /dir/to/search/for/imageset/assets
    templateName: swift4
    output: Assets.swift

This will generate an enum Asset with one case per image set in your assets catalog, so that you can use them as constants.

Example of code generated by the bundled template
enum Asset {
  enum Exotic {
    static let banana: AssetType = "Exotic/Banana"
    static let mango: AssetType = "Exotic/Mango"
  static let `private`: AssetType = "private"

Usage Example

// You can create new images with the convenience constructor like this:
let bananaImage = UIImage(asset: Asset.Exotic.banana)  // iOS
let privateImage = NSImage(asset: Asset.private)  // macOS

// Or as an alternative, you can refer to enum instance and call .image on it:
let sameBananaImage = Asset.Exotic.banana.image
let samePrivateImage = Asset.private.image


  inputs: /path/to/colors-file.txt
    templateName: swift4
    output: Colors.swift

This will generate a enum ColorName with one case per color listed in the text file passed as argument.

The input file is expected to be either:

  • a plain text file, with one line per color to register, each line being composed by the Name to give to the color, followed by ":", followed by the Hex representation of the color (like rrggbb or rrggbbaa, optionally prefixed by # or 0x) or the name of another color in the file. Whitespaces are ignored.
  • a JSON file, representing a dictionary of names -> values, each value being the hex representation of the color
  • a XML file, expected to be the same format as the Android colors.xml files, containing tags <color name="AColorName">AColorHexRepresentation</color>
  • a *.clr file used by Apple's Color Palettes.

For example you can use this command to generate colors from one of your system color lists:

  inputs: ~/Library/Colors/MyColors.clr
    templateName: swift4
    output: Colors.swift

Generated code will look the same as if you'd use a text file.

Example of code generated by the bundled template

Given the following colors.txt file:

Cyan-Color       : 0xff66ccff
ArticleTitle     : #33fe66
ArticleBody      : 339666
ArticleFootnote  : ff66ccff
Translucent      : ffffffcc

The generated code will look like this:

struct ColorName {
  let rgbaValue: UInt32
  var color: Color { return Color(named: self) }

  /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#339666"></span>
  /// Alpha: 100% <br/> (0x339666ff)
  static let articleBody = ColorName(rgbaValue: 0x339666ff)
  /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span>
  /// Alpha: 100% <br/> (0xff66ccff)
  static let articleFootnote = ColorName(rgbaValue: 0xff66ccff)


Usage Example

// You can create colors with the convenience constructor like this:
let title = UIColor(named: .articleBody)  // iOS
let footnote = NSColor(named: .articleFootnote) // macOS

// Or as an alternative, you can refer to enum instance and call .color on it:
let sameTitle = ColorName.articleBody.color
let sameFootnote = ColorName.articleFootnote.color

This way, no need to enter the color red, green, blue, alpha values each time and create ugly constants in the global namespace for them.

Core Data

  inputs: /path/to/model.xcdatamodeld
    templateName: swift4
    output: CoreData.swift

This will parse the specified core data model(s), generate a class for each entity in your model containing all the attributes, and a few extensions if needed for relationships and predefined fetch requests.

Example of code generated by the bundled template
internal class MainEntity: NSManagedObject {
  internal class func entityName() -> String {
    return "MainEntity"

  internal class func entity(in managedObjectContext: NSManagedObjectContext) -> NSEntityDescription? {
    return NSEntityDescription.entity(forEntityName: entityName(), in: managedObjectContext)

  @nonobjc internal class func fetchRequest() -> NSFetchRequest<MainEntity> {
    return NSFetchRequest<MainEntity>(entityName: entityName())

  @NSManaged internal var attributedString: NSAttributedString?
  @NSManaged internal var binaryData: Data?
  @NSManaged internal var boolean: Bool
  @NSManaged internal var date: Date?
  @NSManaged internal var float: Float
  @NSManaged internal var int64: Int64
  @NSManaged internal var manyToMany: Set<SecondaryEntity>

// MARK: Relationship ManyToMany

extension MainEntity {
  @NSManaged public func addToManyToMany(_ value: SecondaryEntity)

  @NSManaged public func removeFromManyToMany(_ value: SecondaryEntity)

  @NSManaged public func addToManyToMany(_ values: Set<SecondaryEntity>)

  @NSManaged public func removeFromManyToMany(_ values: Set<SecondaryEntity>)

Usage Example

// Fetch all the instances of MainEntity
let request = MainEntity.fetchRequest()
let mainItems = try myContext.execute(request)

// Type-safe relationships: `relatedItem` will be a `SecondaryEntity?` in this case
let relatedItem = myMainItem.manyToMany.first


  inputs: /path/to/font/dir
    templateName: swift4
    output: Fonts.swift

This will recursively go through the specified directory, finding any typeface files (TTF, OTF, …), defining a struct FontFamily for each family, and an enum nested under that family that will represent the font styles.

Example of code generated by the bundled template
enum FontFamily {
  enum SFNSDisplay: String, FontConvertible {
    static let regular = FontConvertible(name: ".SFNSDisplay-Regular", family: ".SF NS Display", path: "SFNSDisplay-Regular.otf")
  enum ZapfDingbats: String, FontConvertible {
    static let regular = FontConvertible(name: "ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")

Usage Example

// You can create fonts with the convenience constructor like this:
let displayRegular = UIFont(font: FontFamily.SFNSDisplay.regular, size: 20.0) // iOS
let dingbats = NSFont(font: FontFamily.ZapfDingbats.regular, size: 20.0)  // macOS

// Or as an alternative, you can refer to enum instance and call .font on it:
let sameDisplayRegular = FontFamily.SFNSDisplay.regular.font(size: 20.0)
let sameDingbats = FontFamily.ZapfDingbats.regular.font(size: 20.0)

Interface Builder

  inputs: /dir/to/search/for/storyboards
    - templateName: scenes-swift4
      output: Storyboard Scenes.swift
    - templateName: segues-swift4
      output: Storyboard Segues.swift

This will generate an enum for each of your NSStoryboard/UIStoryboard, with respectively one case per storyboard scene or segue.

Example of code generated by the bundled template

The generated code will look like this:

// output from the scenes template

enum StoryboardScene {
  enum Dependency: StoryboardType {
    static let storyboardName = "Dependency"

    static let dependent = SceneType<UIViewController>(storyboard: Dependency.self, identifier: "Dependent")
  enum Message: StoryboardType {
    static let storyboardName = "Message"

    static let messagesList = SceneType<UITableViewController>(storyboard: Message.self, identifier: "MessagesList")

// output from the segues template

enum StoryboardSegue {
  enum Message: String, SegueType {
    case customBack = "CustomBack"
    case embed = "Embed"
    case nonCustom = "NonCustom"
    case showNavCtrl = "Show-NavCtrl"

Usage Example

// You can instantiate scenes using the `instantiate` method:
let vc = StoryboardScene.Dependency.dependent.instantiate()

// You can perform segues using:
vc.perform(segue: StoryboardSegue.Message.embed)

// or match them (in prepareForSegue):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  switch StoryboardSegue.Message(segue) {
  case .embed?:
    // Prepare for your custom segue transition, passing information to the destionation VC
  case .customBack?:
    // Prepare for your custom segue transition, passing information to the destionation VC
    // Other segues from other scenes, not handled by this VC


  inputs: /path/to/json/dir-or-file
    templateName: runtime-swift4
    output: JSON.swift
  inputs: /path/to/yaml/dir-or-file
    templateName: inline-swift4
    output: YAML.swift

This will parse the given file, or when given a directory, recursively search for JSON and YAML files. It will define an enum for each file (and documents in a file where needed), and type-safe constants for the content of the file.

Unlike other subcommands, this parser is intended to allow you to use more custom inputs (as the formats are quite open to your needs) to generate your code. This means that for these subcommands (and the plist one), you'll probably be more likely to use custom templates to generate code properly adapted/tuned to your inputs, rather than using the bundled templates. To read more about writing your own custom templates, see see the dedicated documentation.

Example of code generated by the bundled template
internal enum JSONFiles {
  internal enum Info {
    private static let _document = JSONDocument(path: "info.json")
    internal static let key1: String = _document["key1"]
    internal static let key2: String = _document["key2"]
    internal static let key3: [String: Any] = _document["key3"]
  internal enum Sequence {
    internal static let items: [Int] = objectFromJSON(at: "sequence.json")

Usage Example

// This will be an dictionary
let foo = JSONFiles.Info.key3

// This will be an [Int]
let bar = JSONFiles.Sequence.items


  inputs: /path/to/plist/dir-or-file
    templateName: runtime-swift4
    output: Plist.swift

This will parse the given file, or when given a directory, recursively search for Plist files. It will define an enum for each file (and documents in a file where needed), and type-safe constants for the content of the file.

Unlike other subcommands, this parser is intended to allow you to use more custom inputs (as the format is quite open to your needs) to generate your code. This means that for this subcommand (and the json and yaml ones), you'll probably be more likely to use custom templates to generate code properly adapted/tuned to your inputs, rather than using the bundled templates. To read more about writing your own custom templates, see see the dedicated documentation.

Example of code generated by the bundled template
internal enum PlistFiles {
  internal enum Test {
    internal static let items: [String] = arrayFromPlist(at: "array.plist")
  internal enum Stuff {
    private static let _document = PlistDocument(path: "dictionary.plist")
    internal static let key1: Int = _document["key1"]
    internal static let key2: [String: Any] = _document["key2"]

Usage Example

// This will be an array
let foo = PlistFiles.Test.items

// This will be an Int
let bar = PlistFiles.Stuff.key1


  inputs: /path/to/Localizable.strings
    templateName: structured-swift4
    output: Strings.swift

This will generate a Swift enum L10n that will map all your Localizable.strings (or other tables) keys to a static let constant. And if it detects placeholders like %@,%d,%f, it will generate a static func with the proper argument types instead, to provide type-safe formatting. Note that all dots within the key are converted to dots in code.

Example of code generated by the structured bundled template

Given the following Localizable.strings file:

"alert_title" = "Title of the alert";
"alert_message" = "Some alert body there";
"apples.count" = "You have %d apples";
"bananas.owner" = "Those %d bananas belong to %@.";

Reminder: Don't forget to end each line in your *.strings files with a semicolon ;! Now that in Swift code we don't need semi-colons, it's easy to forget it's still required by the Localizable.strings file format 😉

The generated code will contain this:

enum L10n {
  /// Some alert body there
  static let alertMessage = L10n.tr("alert_message")
  /// Title of the alert
  static let alertTitle = L10n.tr("alert_title")

  enum Apples {
    /// You have %d apples
    static func count(_ p1: Int) -> String {
      return L10n.tr("apples.count", p1)

  enum Bananas {
    /// Those %d bananas belong to %@.
    static func owner(_ p1: Int, _ p2: String) -> String {
      return L10n.tr("bananas.owner", p1, p2)

Usage Example

Once the code has been generated by the script, you can use it this way in your Swift code:

// Simple strings
let message = L10n.alertMessage
let title = L10n.alertTitle

// with parameters, note that each argument needs to be of the correct type
let apples = L10n.Apples.count(3)
let bananas = L10n.Bananas.owner(5, "Olivier")

Flat Strings Support

SwiftGen also has a template to support flat strings files (i.e. no dot syntax). The advantage is that your keys won't be mangled in any way, the disadvantage is worse auto-completion.

Example of code generated by the flat bundled template
enum L10n {
  /// Some alert body there
  case alertMessage
  /// Title of the alert
  case alertTitle
  /// You have %d apples
  case applesCount(Int)
  /// Those %d bananas belong to %@.
  case bananasOwner(Int, String)

Given the same Localizable.strings as above the usage will now be:

// Simple strings
let message = L10n.alertMessage
let title = L10n.alertTitle

// with parameters, note that each argument needs to be of the correct type
let apples = L10n.applesCount(3)
let bananas = L10n.bananasOwner(5, "Olivier")


This code and tool is under the MIT Licence. See the LICENCE file in this repository.


This tool is powered by

It is currently mainly maintained by @AliSoftware and @djbe. But I couldn't thank enough all the other contributors to this tool along the different versions which helped make SwiftGen awesome! 🎉

If you want to contribute, don't hesitate to open a Pull Request, or even join the team!

Other Libraries / Tools

If you want to also get rid of String-based APIs not only for your ressources, but also for UITableViewCell, UICollectionViewCell and XIB-based views, you should take a look at my Mixin Reusable.

If you want to generate Swift code from your own Swift code (so meta!), like generate Equatable conformance to your types and a lot of other similar things, use Sourcery.

SwiftGen and Sourcery are complementary tools. In fact, Sourcery uses Stencil too, as well as SwiftGen's StencilSwiftKit so you can use the exact same syntax for your templates for both!

You can also follow me on twitter for news/updates about other projects I am creating, or read my blog.


Stars: 5987

Used By

Total: 0


6.1.0 - 2019-01-29 18:46:28

Changes in core dependencies of SwiftGen

New Features

Bug Fixes

  • Colors: Fix an issue where the public access modifier was not being added correctly in the literals-swift3 and literals-swift4 templates when the publicAccess parameter was specified. Also remove some uneccessary public access modifiers from the swift3 and swift4 templates.
    Isaac Halvorson #549

Internal Changes

  • Resolve path if the binary is a symbolic link in order to find bundled templates.
    Liquidsoul #559
  • Update to SwiftLint 0.30.1 and enable some extra SwiftLint rules.
    David Jennes #574 #583

6.0.2 - 2018-10-07 22:17:13

Changes in other SwiftGen modules

Bug Fixes

  • Strings: rolled back the changes in #503, to ensure %% is correctly unescaped.
    David Jennes #542
  • Strings: generate the correct types for %c and %p.
    David Jennes #543
  • SPM/Mint: SwiftGen now provides correct version information, instead of "0.0".
    David Jennes #544

6.0.1 - 2018-10-04 01:02:32

Changes in other SwiftGen modules

Bug Fixes

Internal Changes

6.0.0 - 2018-09-29 01:06:51

⚠️ This major version is a big milestone in which a lot of refactoring and cleaning has been done. Many features added over previous releases have been reworked and unified, while also preparing SwiftGen for future additions. This means that you'll need to adapt your configuration files (or command line invocations) and custom templates to work with this new major version.

Read the SwiftGen 6.0 Migration Guide for a list of changes you'll need to apply.

Changes in other SwiftGen modules

Breaking Changes

  • Don't normalize string keys while parsing, let all transformation be done on template side. This makes the developer responsible to keep the language file organized, duplications won't be removed.
    Diego Chohfi #257
  • Remove Swift 2 support.
    David Jennes #420
  • Renamed the storyboards command to ib, to better reflect it's purpose. An alias for storyboards still exists, but it will be removed at some point.
    David Jennes #423
  • XCAssets: the generated templates won't namespace groups by default anymore, use the forceProvidesNamespaces flag to enable this behaviour again.
    jechris #453
  • XCAssets: the templates won't generate any all-values accessors anymore by default. Use the allValues flag to enable this behaviour again. Note: this replaces the old noAllValues flag (with an inverse behaviour).
    David Jennes #480
  • XCAssets: Dropped the deprecated allValues constant, use the type specific constants such as allColors, allDataItems and allImages. The default value of imageAlias has also been changed from Image to AssetImageTypeAlias, to be consistent with the other types.
    David Jennes #482
  • Interface Builder: split up the storyboards template into 2 parts, one for scenes and one for segues.
    David Jennes #419

New Features

  • Add ability to list all custom fonts and register them using FontFamily.registerAllCustomFonts.
    Olivier Halligon #394
  • Add support for Swift Package Manager and Mint.
    Yonas Kolb #411
  • The swiftgen.yml config file now accepts multiple outputs for each command, allowing you to generate multiple outputs from the same files and content. This also means that the output parameter is now deprecated, in favour of the outputs parameter, and it may be removed in a future version of SwiftGen. Similarly, the paths parameter has been renamed to inputs for consistency. You can always use swiftgen config lint to validate your configuration file.
    David Jennes #424 #510
  • Use swiftlint:disable all in generated files to avoid interference with SwiftLint rules custom to the host project.
    Frederick Pietschmann David Jennes #409 #506
  • XCAssets: Added support for NSDataAssets.
    Oliver Jones #444
  • Organised the generated code in sections for better readability, with all generated constants at the top of the file.
    David Jennes Olivier Halligon #456 #481
  • Added support for JSON, Plist and YAML files using the swiftgen json, swiftgen plist and swiftgen yaml commands. The parsed contexts and the generated files for each command have been kept quite similar, for easier switching between file formats.
    John T McIntosh Toshihiro Suzuki Peter Livesey David Jennes #379 #359 #288 #188 #493 #504
  • Updated the playgrounds with the new json, plist and yaml commands, and updated the other pages to reflect the template changes.
    David Jennes #495
  • We're deprecating the old --template CLI option in favor of --templateName, to better match the naming of the other options and the configuration file. The old --template option will remain until the next major version.
    David Jennes #509

Bug Fixes

  • Fix memory leak in generated code for Fonts.
    Olivier Halligon #394
  • Interface Builder: ensure the templates handle GLKViewController, AVPlayerViewController and NSPageController correctly.
    David Jennes #404 #414
  • Interface Builder: ensure the parser can handle files with and without "trait variations".
    David Jennes #367 #429
  • Restrict SceneType and InitialSceneType to UIViewController when not targeting AppKit. When targeting AppKit, remove superfluous Any.
    Darron Schall #463 #464
  • Fonts: disable a warning in generated font files for projects with conditional_returns_on_newlines SwiftLint rule enabled.
    Ryan Davies #436 #465
  • Interface Builder: the parser and templates now handle the "Inherit module from target" setting.
    David Jennes #435 #485
  • Strings: the parser now correctly handles formats such as % d and %#x.
    David Jennes #502
  • Strings: ensure strings without arguments are not processed using String(format:).
    David Jennes #503

Internal Changes

5.3.0 - 2018-05-16 19:15:46

Changes in other SwiftGen modules

New Features

Internal Changes

  • Merged the SwiftGenKit and templates repositories back into this repository for easier development and maintenance.
    David Jennes #356

5.2.1 - 2017-10-24 12:47:20

Bug Fixes

  • Fix SwiftGen no longer working using CLI parameters (instead of config file).
    David Jennes #347
  • Errors now properly exit with a non-zero exit code.
    Olivier Halligon #348
  • swiftgen --help prints the full help back again (and not just the help of the default config run subcommand).
    Olivier Halligon #349

5.2.0 - 2017-10-22 17:20:05

Changes in other SwiftGen modules

New Features

Bug Fixes

5.1.2 - 2017-09-25 20:38:11

5.1.1 - 2017-08-21 17:02:15

Changes in other SwiftGen modules

Bug Fixes

5.1.0 - 2017-08-20 18:54:34

Changes in other SwiftGen modules

New Features

  • Added Swift 4 templates. Use -t swift4 or whatever variant you want to use (see swiftgen templates list for the available names).
    David Jennes SwiftGen/templates/#67
  • XCAssets: Added support for named colors. When using swiftgen xcassets the bundled templates will now also include colors found in the Asset Catalog in addition to the images.
    David Jennes SwiftGen/templates/#68
  • Fonts: the path to fonts will now default to just the font filename, but you can disable this behaviour by enabling the preservePath parameter.
    David Jennes SwiftGen/templates/#71
  • Colors: new template that uses #colorLiterals.
    Use swiftgen colors -t literals-swift3 / swiftgen colors -t literals-swift4 to use them.
    David Jennes SwiftGen/templates/#72

5.0.0 - 2017-08-12 17:16:01

⚠️ This major version is a big milestone in which a lot of refactoring and cleaning has been done. Many features added over previous releases have been reworked and unified, while also preparing SwiftGen for future additions. This means that you'll need to adapt your command line invocations and custom templates to work with this new major version.

Read the SwiftGen 5.0 Migration Guide for a list of changes you'll need to apply.

Changes in other SwiftGen modules

Breaking Changes

  • Removed deprecated CLI options. Please consult the migration guide should you still use them.
    David Jennes #301
  • Disable default value for named template option and ensure that there is a template option.
    Liquidsoul #283
  • Templates are now grouped by subcommand on the filesystem. This is only important if you had custom templates in the Application Support directory. To migrate your templates, place them in a subfolder with the name of the subcommand, and remove the prefix of the template filename.
    David Jennes #304
  • The images command has been renamed to xcassets to better reflect its functionality.
    Olivier Halligon #317

Notable breaking changes from other SwiftGen repositories

New Features

Internal Changes

Notable internal changes from other SwiftGen repositories

  • Switch back from actool to an internal parser to fix numerous issues with the former. This fixes issues a few people encountered when using asset catalogs that contained some of the less common set types.
    David Jennes #228 SwiftGen/SwiftGenKit#43

4.2.1 - 2017-05-09 03:51:32

• 🔗 SwiftGenKit 1.1.0 • 🔗 StencilSwiftKit 1.0.2 • 🔗 Stencil 0.9.0 • 🔗 templates 1.1.0

Bug Fixes

  • Fix a bug in which the version of SwiftGen was reported as v0.0 by swiftgen --version.
    Olivier Halligon

Internal Changes

4.2.0 - 2017-02-20 08:16:00

• 🔗 SwiftGenKit 1.0.1 • 🔗 StencilSwiftKit 1.0.0 • 🔗 Stencil 0.8.0 • 🔗 templates 1.0.0

ℹ️ Don't forget to look at the CHANGELOGs of the other repositories too (links above) in addition to this one, to see all the changes across all of SwiftGen.

Bug Fixes

Notable bug fixes from other SwiftGen repositories

New Features

  • You can now pass custom parameters to your templates using the --param X=Y syntax.
    @djbe #265
    • This command-line option can be repeated at will and used to pass structured custom parameters (e.g. --param tabs=2 --param foo.bar=1 --param foo.baz=2).
    • You can then use them in your templates using e.g. {{param.tabs}}, {{param.foo.bar}} & {{param.foo.baz}}.
  • Templates can now access environment variables via the env key of the Stencil context (e.g. {{env.USER}}, {{env.LANG}}).
    @djbe #265
    • This is especially useful when integrating SwiftGen as a Script Build Phase in your Xcode project as you can then access Xcode Build Settings exposed as environment variables by Xcode, e.g. {{env.PRODUCT_MODULE_NAME}}.

Notable new features from other SwiftGen repositories


In preparation for an upcoming cleanup of SwiftGen to remove some legacy code as well as Stencil old variables, tags and filters, and change the default templates to Swift 3, some things are being deprecated and will be removed in the next major version 5.0.

As a result, if you wrote custom templates, you should already prepare for the upcoming 5.0 by migrating your templates to use the new variables (already avaiable in SwiftGen 4.2 / SwiftGenKit 1.0).

See #244 and the Migration Guide in the Wiki for a list of deprcations and their replacements.

Internal changes

  • SwiftGen has migrated to its own GitHub organization 🎉.
  • SwiftGen has been split in multiple repositories and separate modules.
    @AliSoftware @djbe #240 #265
    • The present SwiftGen is the CLI parsing. It is in charge of calling the frameworks, feeding them appropriate parameters according to the command line arguments.
    • SwiftGenKit is the framework responsible for parsing your assets/resources and turning them into a structured representation compatible with Stencil templates.
    • StencilSwiftKit is a framework adding some extensions to the template engine Stencil used by SwiftGen. It adds some tags and filters as well as convenience methods shared both by SwiftGen itself and by Sourcery.
    • The SwiftGen templates has been moved into a dedicated templates repo so they can evolve and be unit-tested separately of SwiftGen.

Note: The next minor version will focus on bringing more documentation for all this new structure and improve ease of future contributions.

4.1.0 - 2017-01-03 19:01:54

Bug Fixes

  • Strings: fix issue with dot-syntax-swift3 where function definitions were not Swift 3 guidelines compliant.
    David Jennes #248
  • Snake cased keys with uppercase letters are correctly camel cased again. Cihat Gündüz #226

New Features

  • Added a storyboards-osx-swift3 template.
    Felix Lisczyk #225
  • Added a strings-no-comments-swift3 template that does not include the default translation of each key.
    Loïs Di Qual #222
  • Images: new dot-syntax template, use dot-syntax-swift3 or dot-syntax (for Swift 2.3).
    David Jennes #206
  • Reworked the "dot-syntax" and "structured" templates to use the new macro and call tags, which greatly simplifies the templates, and also removes the limitation of 5-level deep structures.
    David Jennes #237
  • Storyboards: automatically detect the correct modules that need to be imported. The --import option has therefore been deprecated, as well as the extraImports template variable. Instead use the the new modules variable, which offers the same functionality.
    David Jennes #243
  • Support multiple input paths for some commands:
    David Jennes #213
    • fonts accepts multiple input directories, all found fonts will be added to the families template variable.
    • images now supports multiple asset catalogs as input. Templates can now use the catalogs variable to access each individual catalog.
    • storyboards accepts multiple paths (to folders or storyboard files). All found storyboards will be available in the storyboards template variable.

Internal changes

4.0.1 - 2016-12-04 01:02:53

Bug Fixes

Internal changes

4.0.0 - 2016-11-20 18:23:15

  • Add support for multiline string in *.strings file.
    Jeong Yonguk #192
  • Change swift 3 storyboard segue template's sender from AnyObject to Any.
    Derek Ostrander #197
  • Fix swift 3 storyboard templates to be compliant with swift 3 api design guidelines.
    Afonso #194
  • Add option to add import statements at the top of the generated swift file (for storyboards) using the import flag. Multiple imports can be added by repeating this flag.
    David Jennes #175
  • Remove the key param label from the tr function for Localized String in the swift3 template.
    AndrewSB #190
  • Escape reserved swift keywords in the structured and dot-syntax generated strings code.
    Afonso #198
  • The swiftgen images command now uses the actool utility to parse asset catalogs, ensuring that the parser correctly handles namespaced folders.
    David Jennes #199

3.0.1 - 2016-11-06 19:11:54

3.0.0 - 2016-09-04 17:46:13

  • Add template that calls NSLocalizedString() separately for each string, which is useful when trying to extract strings in the app to a .strings file.
    Ahmet Karalar
  • Add some file_length and similar SwiftLint exceptions in bundled templates, as files generated by SwiftGen might contain lots of constants and can be long by design.
    Olivier Halligon
  • Error messages ("template not found", etc) are now printed on stderr.
    Olivier Halligon
  • Add more swiftgen templates subcommands.
    Olivier Halligon
    • swiftgen templates list lists all the available templates
    • swiftgen templates which <name> prints the path to the template named <name>
    • swiftgen templates cat <name> prints the content to the template named <name>
    • <name> here can be either a subcommand name like colors or a composed name colors-rawValue for a specific template.
  • Fix swift 3 renaming change in strings-swift3.stencil.
    Kilian Koeltzsch, #150
  • Fix non-custom class, non-base view controller handling in storyboards-swift3.stencil.
    Syo Ikeda, #152
  • Add strongly typed initialViewController() overrides for storyboard templates if available.
    Syo Ikeda, #153, #163
  • Add support for font files containing multiple descriptors.
    Chris Ellsworth, #156
  • Update deprecated usage of generics for Swift 3 / Xcode 8 beta 6.
    Chris Ellsworth, #158
  • Fix case when missing positional parameters, which leads to parameters in the enum with unspecified type (undeterminable from the Localizable.strings format analysis) where reported as Any — which is not a CVarArgType. Now using UnsafePointer<()> arguments instead for such odd edge-cases that should never happen anyway.
    Olivier Halligon
  • Now reports an error when it failed to parse a color in a color input file.
    Olivier Halligon, #162
  • New Strings template (available via -t dot-syntax), allowing string keys containing dots (like foo.bar.baz) to be organized as a hierarchy and accessible via dot syntax. Cihat Gündüz, #159
  • Update Swift 3 templates to use lowercase enums.
    Olivier Halligon, #166
  • New Strings template (available via -t dot-syntax-swift3), allowing keys with dots in Swift 3 (see above).
    Cihat Gündüz, #168

💡 You can now create your custom templates more easier than ever, by cloning an existing template!

e.g. to clone the default strings-default.stencil template:

  • use swiftgen templates cat strings --output strings-custom.stencil
  • modify the cloned strings-custom.stencil template to your liking
  • use it with swiftgen strings … --templatePath strings-custom.stencil … in your projects!

Important Notes

  • Some keys for various templates have changed to provide more flexibility and enable some new features in the templates. As a result, if you created your own custom templates, they might not all be totally compatible with SwiftGen 3.0.0 (hence the new major version). Please read the Custom Templates documentation to find out the new Stencil context keys and update your custom templates accordingly.

If you're using one of the bundled templates, all of them have been updated appropriately.

  • Also if you use Swift 3, and thus use the -t swift3 flag to use the Swift 3 templates, be advised those has been modified to take the latest Swift 3 modifications into account (including naming convensions) so your code might need to be updated according to match the latest Swift 3 recommendations.

2.0.0 - 2016-06-28 23:59:25

Note: The Stencil context keys (the name of the variables used in templates) for storyboard has changed a bit. Especially, class has been renamed into customClass (see #131) to better describe the intent (as this isn't defined if there is no custom class set in the Storyboard), and new keys isBaseViewController and baseType has been added.

This means that if you did implement your own custom templates for storyboards (instead of using the bundled ones), you'll have to remplace {{class}} by {{customClass}} in those storyboard templates, otherwise they'll probably stop working as expected. That's the main reason why the version has been bumped to a major version 2.0.0.

1.1.2 - 2016-06-09 13:11:50

  • Fix issue introduced by 1.1.1 in storyboard templates not returning.
    Ben Chatelain #138

1.1.1 - 2016-06-08 21:22:43

1.1.0 - 2016-06-06 11:02:43

1.0.0 - 2016-06-01 23:30:26

  • Restructured colors & fonts templates to workaround the same LLVM issue as #112 with nested types inside existing UIKit classes in Release/Optimized builds.
    Olivier Halligon
  • Added support for Fonts using the swiftgen fonts command.
    Derek Ostrander #102
  • Added support for TXT (colors.txt) files to have named value.
    Derek Ostrander, #118
  • Restructured image templates to work around an LLVM issue with nested types.
    Ken Grigsby, #112
  • Added Swift 3 templates for storyboards and strings.
    Andrew Breckenridge, #117

0.8.0 - 2016-03-13 20:05:32

  • Introducing alternative way to install SwiftGen: using CocoaPods! See README for more details.
    Olivier Halligon, #95
  • Added support for JSON (colors.json) files as input for the swiftgen colors subcommand.
    Derek Ostrander
  • Use String(format:locale:arguments:) and the NSLocale.currentLocale() in the "string" templates so that it works with .stringdict files and pluralization.
    Olivier Halligon, #91
  • Add support for Android colors.xml files as input for the swiftgen colors subcommand.
    Olivier Halligon, #15
  • Removed the useless import Foundation from the "images" templates.
    Olivier Halligon
  • Added computed property var color: UIColor to the color templates.
    Olivier Halligon

- 2016-02-19 21:09:25


  • Fixed build loop by changing SwiftGen to only write to the output file if the generated code is different from the file contents.
    Mathias Nagler, #90


  • Fixed typos in code and descriptions: instanciate -> instantiate. Please note that the default template used for storyboards storyboards-default.stencil had to be modified, so make sure to update your codebase accordingly.
    Pan Kolega, #83
  • Fixed issue in Rakefile when trying to install via rake in a path containing ~.
    Jesse Armand, #88

- 2016-02-19 21:09:16


  • Updated stencils and unit tests to pass SwiftLint.
    Adam Gask, #79
  • Updated storyboards-default.stencil to better avoid name confusions.
    Olivier Halligon
    • Now cases names are suffixed with …Scene and static func are prefixed with instantiate… to lower the risks of a name conflict with your ViewController classes.
    • The old template is still available but has been renamed storyboards-uppercase.stencil
  • Added support for *.clr files (files to store NSColorList's presented in Color Picker on "Color Palettes" tab)
    Ilya Puchka, #81

- 2016-02-19 21:08:59


- 2016-02-19 21:08:45


  • Restructured storyboard templates to work around an LLVM issue with nested types.
    Ryan Booker, #57

Scenes and Segues are now referenced via StoryboardScene.<Storyboard> and StoryboardSegue.<Storyboard>.<Segue>

- 2016-02-19 21:08:19


  • Adding comments to generated color enums which allow you to see the color in the QuickHelp documentation

colors QuickHelp

  • The default translation of strings are now added as documentation comments to the enum cases.
    You can add translations to your own templates by using the string.translation variable.
    @MrAlek, #58, #60


  • Fix an issue with the colors template due to an Apple Bug when building in Release and with WMO enabled.

- 2016-02-19 21:07:55


  • Fix issue with swiftgen strings that were using the colors templates instead of the strings template by default.
    @ChristopherRogers, #54