templates Documentation

Stencil templates for SwiftGen

13 stars Swift Swift 26 files ยท ~18,023 tokens
RAW Doc

Technical Documentation: SwiftGen/templates

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

:warning: Deprecated :warning:

This repository has been merged into the main SwiftGen repository.

SwiftGen Templates

This repository contains Stencil templates that are dedicated for being used with SwiftGen.

What are templates for?

The aim of SwiftGen is to parse your resources (asset catalogs, fonts, storyboards, โ€ฆ) and generate Swift code (constants, etc) from them.

But everybody can have a different code style policy about what they want the generated code to look like:

  • Some people prefer a different level of indentation than others, some prefer tabs, some prefer spaces
  • Some people are still using Swift 2, while some other people need the generated code to be Swift 3.
  • Some people will prefer the generated code to be hierarchical, some will prefer a flat list of constants.
  • Some people will want different names for the generated structures or enums
  • Some people will have special needs about the generated code

And that's exactly what templates are for: to allow people to describe how they want their generated code to look like so that the generated code will fit exactly what they need.

How do they work with SwiftGen?

In practice, when SwiftGen parses your various resources (images, fonts, โ€ฆ), it generates a dictionary representation of those resources (an array of image names, an array of dictionaries representing a font with all its variants, etc), that is then used as the input for the template you choose to use.

For example, when parsing an asset catalog, SwiftGen will generate a dictionary representation like this:

text
[
  "assets": [
    "foo",
    "bar",
    "baz",
  ]
]

(this is a partial example for the sake of simplifying the explanation; see the documentation for the full generated structure for each command)

Then this dictionary is used as input to feed your templates with variables. In your template, you can access the variable named assets and iterate over each string inside it to generate some Swift code as needed. For example if your template mytemplate.stencil looks like this:

text
enum Assets: String {
  {% for asset in assets %}
  case {{asset}} = "{{asset}}"
  {% endfor %}
}

Then, given the above dictionary generated internally by SwiftGen when parsing your asset catalog, the generated code will look like this:

text
enum Assets: String {
  case foo = "foo"
  case bar = "bar"
  case baz = "baz"
}

To use that template, you'd simply invoke SwiftGen using swiftgen xcassets -p path/to/mytemplate.stencil path/to/your/Images.xcassets and SwiftGen will use that custom template of yours at the specified path.

Stencil

SwiftGen uses Stencil as its template engine.
This means that you'll use the syntax explained in Stencil's documentation to write your templates for SwiftGen.
See the Stencil dedicated documentation for more information.

Templates bundled with SwiftGen

SwiftGen comes bundled with commonly used templates for the various type of resources.

For each type of resource (images, fonts, etcโ€ฆ), SwiftGen provides a number of templates for common use cases (at least one for each swift version), that you can select using the -t option when invoking SwiftGen (e.g. swiftgen xcassets -t swift2 path/to/your/Images.xcassets). The -t and -p options have the same purpose (selecting a specific template you want to use when asking SwiftGen to generate the output Swift code), -t simply selects the template by name (looking for a template with this name among the templates bundled with SwiftGen itself) while -p allows you to indicate an arbitrary template using a path.

Templates documentation

You can find the documentation for each template โ€” including its name, typical use case, what can be customized in it, how the typical generated output will look like, etc โ€” in the Documentation directory in this repository.

This can help you choose which template is right for you depending on your needs and use case. Keep in mind that some templates can be customized by providing parameters such as --param enumName=MyEnum. Each template documents the supported parameters and their purpose.

Creating your own templates

Creating your own templates is just a matter of creating a Stencil template (using the tags and filters you need using the syntax documented in Stencil) then use it.

The best way to start creating your own template is by duplicating an existing template as a starting point, then modifying the copy to your needs. You can do that easily using the following commands:

sh
# Duplicate the xcassets swift3.stencil template and redirect the output to a new mytemplate.stencil file
$ swiftgen templates cat xcassets swift3 > mytemplate.stencil
# Then modify the duplicated template using your favorite text editor to tweak it to your needs
$ edit mytemplate.stencil
# Then use your new template instead of the swift3 one when invoking SwiftGen
$ swiftgen xcassets -p mytemplate.stencil path/to/your/Images.xcassets

To learn more about creating your own template, see the dedicated documentation in the documentation/ directory of this repository.


Overview (`Pods/PathKit/README.md`)

PathKit

Effortless path operations in Swift.

Usage

swift
let path = Path("/usr/bin/swift")

Joining paths

swift
let path = Path("/usr/bin") + Path("swift")

Determine if a path is absolute

swift
path.isAbsolute()

Determine if a path is relative

swift
path.isRelative()

Determine if a file or directory exists at the path

swift
path.exists()

Determine if a path is a directory

swift
path.isDirectory()

Get an absolute path

swift
let absolutePath = path.absolute()

Normalize a path

This cleans up any redundant .. or . and double slashes in paths.

swift
let normalizedPath = path.normalize()

Deleting a path

swift
path.delete()

Moving a path

swift
path.move(newPath)

Current working directory

swift
Path.current
Path.current = "/usr/bin"

Changing the current working directory

swift
path.chdir {
  // Path.current would be set to path during execution of this closure
}

Children paths

swift
path.children()

Reading

swift
path.read()

Writing

swift
path.write("Hello World!")

Glob

swift
let paths = Path.glob("*.swift")

Contact

Kyle Fuller

License

PathKit is licensed under the BSD License.


Overview (`Pods/Stencil/README.md`)

Stencil

Stencil is a simple and powerful template language for Swift. It provides a
syntax similar to Django and Mustache. If you're familiar with these, you will
feel right at home with Stencil.

Example

html+django
There are {{ articles.count }} articles.

<ul>
  {% for article in articles %}
    <li>{{ article.title }} by {{ article.author }}</li>
  {% endfor %}
</ul>
swift
import Stencil

struct Article {
  let title: String
  let author: String
}

let context = [
  "articles": [
    Article(title: "Migrating from OCUnit to XCTest", author: "Kyle Fuller"),
    Article(title: "Memory Management with ARC", author: "Kyle Fuller"),
  ]
]

let environment = Environment(loader: FileSystemLoader(paths: ["templates/"]))
let rendered = try environment.renderTemplate(name: context)

print(rendered)

Philosophy

Stencil follows the same philosophy of Django:

If you have a background in programming, or if youโ€™re used to languages which
mix programming code directly into HTML, youโ€™ll want to bear in mind that the
Django template system is not simply Python embedded into HTML. This is by
design: the template system is meant to express presentation, not program
logic.

The User Guide

Resources for Stencil template authors to write Stencil templates:

Resources to help you integrate Stencil into a Swift project:

License

Stencil is licensed under the BSD license. See LICENSE for more
info.


Overview (`Pods/StencilSwiftKit/README.md`)

StencilSwiftKit



StencilSwiftKit is a framework bringing additional Stencil nodes & filters dedicated to Swift code generation.

Tags

  • Macro & Call
    • {% macro <Name> %}โ€ฆ{% endmacro %}
    • Defines a macro that will be replaced by the nodes inside of this block later when called
    • {% call <Name> <Args> %}
    • Calls a previously defined macro, passing it some arguments
  • Set
    • {% set <Name> %}โ€ฆ{% endset %}
    • Renders the nodes inside this block immediately, and stores the result in the <Name> variable of the current context.
  • Map
    • {% map <Variable> into <Name> using %}โ€ฆ{% endmap %}
    • Apply a map operator to an array, and store the result into a new array variable <Name> in the current context.
    • Inside the map loop, a maploop special variable is available (akin to the forloop variable in for nodes). It exposes maploop.counter, maploop.first, maploop.last and maploop.item.

Filters

  • String filters:
    • basename: Get the filename from a path.
    • camelToSnakeCase: Transforms text from camelCase to snake_case. By default it converts to lower case, unless a single optional argument is set to "false", "no" or "0".
    • contains: Check if a string contains a specific substring.
    • dirname: Get the path to the parent folder from a path.
    • escapeReservedKeywords: Escape keywords reserved in the Swift language, by wrapping them inside backticks so that the can be used as regular escape keywords in Swift code.
    • hasPrefix / hasSuffix: Check if a string starts/ends with a specific substring.
    • lowerFirstLetter: Lowercases only the first letter of a string.
    • lowerFirstWord: Lowercases only the first word of a string.
    • removeNewlines: Removes newlines and other whitespace characters, depending on the mode ("all" or "leading").
    • replace: Replaces instances of a substring with a new string.
    • snakeToCamelCase: Transforms text from snake_case to camelCase. By default it keeps leading underscores, unless a single optional argument is set to "true", "yes" or "1".
    • swiftIdentifier: Transforms an arbitrary string into a valid Swift identifier (using only valid characters for a Swift identifier as defined in the Swift language reference). In "pretty" mode, it will also apply the snakeToCamelCase filter afterwards, and other manipulations if needed for a "prettier" but still valid identifier.
    • upperFirstLetter: Uppercases only the first character
  • Number filters:
    • int255toFloat
    • hexToInt
    • percent

StencilSwiftTemplate

This framework also contains a StencilSwiftTemplate class, which is a subclass of Stencil.Template dedicated to remove extra newlines when rendering the template.

Indeed, such extra newlines could otherwise be inserted in the generated output because you want your template to be well formatted, and that can end up with Stencil nodes like {% for โ€ฆ %} and {% if โ€ฆ %} be alone in some lines of your template and that would render into nothing by themselves, generating empty lines in the output.

This template subclass aims to remove those lines generated by using a simple workaround when rendering, until there's an embeded way to handle that in Stencil proper (see Stencil/#22).

Stencil.Extension & swiftStencilEnvironment

This framework also contains helper methods for Stencil.Extension and Stencil.Environment, to easily register all the tags and filters listed above on an existing Stencil.Extension, as well as to easily get a Stencil.Environment preconfigured with both those tags & filters Extension and the StencilSwiftTemplate.

Parameters

This framework contains an additional parser, meant to parse a list of parameters from the CLI. For example, using Commander, if you receive a [String] from a VariadicOption<String>, you can use the parser to convert it into a structured dictionary. For example:

swift
["foo=1", "bar=2", "baz.qux=hello", "baz.items=a", "baz.items=b", "something"]

will become

swift
[
  "foo": "1",
  "bar": "2",
  "baz": [
    "qux": "hello",
    "items": [
      "a",
      "b"
    ]
  ],
  something: true
]

For easier use, you can use the StencilContext.enrich(context:parameters:environment:) function to add the following variables to a context:

  • param: the parsed parameters using the parser mentioned above.
  • env: a dictionary with all available environment variables (such as PATH).

Documentation Creating Your Templates (`Documentation/Creating-your-templates.md`)

Customize SwiftGen templates

This document describes how to make your own templates for SwiftGen, so it can generate code more to your liking and code following your own coding conventions. For in depth documentation of the bundled templates, we refer you to the documentation for each specific template.

Templates files on disk (Search Path priority)

When you invoke SwiftGen, you can specify templates by name or by path.

Using a full path

If you use the --templatePath (or -p) option, you'll need to specify the full path to the template you want to use. This allows you to store your templates anywhere you want and name them anyhow you want, but can become quite annoying to type.

Using a name

When you use the --template (or -t) option, you only specify a template name. SwiftGen then searches a matching template using the following rules (where <subcommand> is one of colors, xcassets, storyboards or strings depending on the subcommand you invoke):

  • It searches for a file named <name>.stencil in ~/Library/Application Support/SwiftGen/templates/<subcommand>/, which is supposed to contain your own custom templates for that particular subcommand.
  • If it does not find one, it searches for a file named <name>.stencil in /share/swiftgen/templates/<subcommand> which contains the templates bundled with SwiftGen for that particular subcommand.

For example swiftgen xcassets -t foo DIR will search for a template named foo.stencil in Application Support, then in /usr/local/share/SwiftGen/templates/xcassets (assuming you installed SwiftGen using Homebrew in /usr/local)

List installed templates

The swiftgen templates list command will list all the installed templates (as YAML output) for each subcommand, both for bundled templates and custom templates.

bash
$ swiftgen templates list
colors:
  custom:
  bundled:
   - swift2
   - swift3
storyboards:
  custom:
   - mytemplate
  bundled:
   - swift2
   - swift3
strings:
  custom:
   - mycustomtemplate
  bundled:
   - flat-swift2
   - flat-swift3
   - structured-swift2
   - structured-swift3
xcassets:
  custom:
  bundled:
   - swift2
   - swift3

Printing a template, creating a new template

You can use the swiftgen templates cat <subcommand> <templatename> command to print the template of that given name for that given subcommand to stdout. e.g. swiftgen templates cat fonts swift3 will print to your terminal the template that would be used if you invoke swiftgen fonts -t swift3 โ€ฆ.

You can use this feature to easily create a new template from an existing one.
In particular, the easiest way to create your own templates is to:

  • duplicate an existing template by dumping it into a new file like this: swiftgen templates cat fonts swift3 >my-custom-fonts-template.stencil
  • then edit the new my-custom-fonts-template.stencil file to make your modifications to that template
  • Once you've done this you can then simply use swiftgen fonts -p my-custom-fonts-template.stencil โ€ฆ to use you customized template!

Templates Format, Nodes and Filters

Templates in SwiftGen are based on Stencil, a template engine inspired by Django and Mustache. The syntax of the templates is explained in Stencil's documentation.

Additionally to the tags and filters provided by Stencil, SwiftGen provides some additional ones, documented in the StencilSwiftKit framework.

Templates Contexts

When SwiftGen generates your code, it provides a context (a dictionary) with the variables containing what assets/colors/strings/โ€ฆ the subcommand did detect, to render your Stencil template using those variables.

A full documentation of the produced context for each command can be found in the SwiftGenKit documentation.


Documentation MigrationGuide (`Documentation/MigrationGuide.md`)

Templates 2.1 Migration Guide

Functionality changes in 2.1 (SwiftGen 5.1)

XCAssets

The static allValues constant has been deprecated in favor of the allImages and allColors constants. This is because we've added support for named colors in asset catalogs.

Templates 2.0 Migration Guide

If you're moving from SwiftGen 4.x to SwiftGen 5.0, you'll need to be aware that some templates have been renamed, removed or merged with others. Follow this Migration Guide to use the new name for SwiftGen 5.x of the templates you were previously using with SwiftGen 4.x.

Deprecated templates in 2.0 (SwiftGen 5.0)

The two general themes for this version are:

  • Templates now reside in the subfolder corresponding to their subcommand (colors, fonts, ...) instead of the filename being prefixed with it.
  • The default template doesn't exist anymore, templates now specify which swift version they support.

Below is a list of renamed ("โžก๏ธ") and removed ("โŒ") templates, grouped by subcommand. If your template hasn't been renamed or removed, you don't need to do anything ("โœ…"). You still might want to review the documentation for that template, as there might be new features you may be interested in.

Colors

Old New Reason
default โžก๏ธ swift2
rawvalues โŒ deleted Seldomly used
swift3 โœ… swift3

Fonts

Old New Reason
default โžก๏ธ swift2
swift3 โœ… swift3

Images / XCAssets

Old New Reason
allvalues โžก๏ธ swift2/swift3 All templates by default now generate an allValues static constant
default โš ๏ธ swift2 Now integrates the recursive features of the previously named dot-syntax template
dot-syntax โžก๏ธ swift2
dot-syntax-swift3 โžก๏ธ swift3
swift3 โš ๏ธ swift3 Now integrates the recursive features of the previously named dot-syntax-swift3 template

โš ๏ธ The images subcommand from SwiftGen 4.x has been renamed xcassets in SwiftGen 5.0, so be sure to put those templates in a xcassets subfolder and not an images subfolder.

Storyboards

Old New Reason
default โžก๏ธ swift2
lowercase โŒ deleted No longer needed since we prefix classes with their module
osx-default โžก๏ธ swift2 Unified with the iOS template, just use swift2
osx-lowercase โŒ deleted No longer needed since we prefix classes with their module
osx-swift3 โžก๏ธ swift3 Unified with the iOS template, just use swift3
swift3 โš ๏ธ swift3 You'll probably need to adapt your call sites. See below.
uppercase โŒ deleted No longer needed since we prefix classes with their module

Strings

Old New Reason
default โžก๏ธ flat-swift2
dot-syntax โžก๏ธ structured-swift2
dot-syntax-swift3 โžก๏ธ structured-swift3
genstrings โŒ deleted Seldomly used
no-comments-swift3 โŒ deleted The other templates now support a noComments parameter
structured โŒ deleted Deprecated by dot-syntax (now called structured-swift2/3)
swift3 โžก๏ธ flat-swift3

Functionality changes in 2.0 (SwiftGen 5.0)

Storyboards

You'll probably notice that your old codebase won't work with the new generated code. This is because we use a new, swiftier way of generating types for storyboard scenes. What it boils down to is that, if you had the following line in your code base:

swift
StoryboardScene.Message.instantiateMessageList()

It should now become:

swift
StoryboardScene.Message.messageList.instantiate()

๐Ÿ’ก Tip: to help you do this transition, you may be interested in using the "compatibility template" we suggest here. It will allow you to generate compatibility code for the old storyboard function calls, generating depreciation warnings + renaming fix-its for that SwiftGen 4.x API. This way you could then use Xcode's "Fix all in scope" feature to let Xcode do the renaming and migration for you!


Documentation Colors Literals Swift3 (`Documentation/colors/literals-swift3.md`)

Template Information

Name Description
File name colors/literals-swift3.stencil
Invocation example swiftgen colors -t literals-swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code
  • Supports multiple color names with the same value
  • Uses #colorLiterals for easy preview of the actual color

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName ColorName Allows you to change the name of the generated enum containing all colors.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Note: if you use --param enumName=UIColor (or NSColor on macOS) then the color constants will be generated as an extension of the UIColor (iOS) / NSColor (macOS) type directly without creating a separate enum type for namespacing those color constants.

Generated Code

Extract:

swift
extension ColorName {
  /// 0x339666ff (r: 51, g: 150, b: 102, a: 255)
  static let articleBody = #colorLiteral(red: 0.2, green: 0.588235, blue: 0.4, alpha: 1.0)
  /// 0xff66ccff (r: 255, g: 102, b: 204, a: 255)
  static let articleFootnote = #colorLiteral(red: 1.0, green: 0.4, blue: 0.8, alpha: 1.0)
}

Full generated code

Usage example

swift
// To reference a color, simpy reference its static instance by name:
let title = ColorName.articleBody
let footnote = ColorName.articleFootnote

Documentation Colors Literals Swift4 (`Documentation/colors/literals-swift4.md`)

Template Information

Name Description
File name colors/literals-swift4.stencil
Invocation example swiftgen colors -t literals-swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code
  • Supports multiple color names with the same value
  • Uses #colorLiterals for easy preview of the actual color

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName ColorName Allows you to change the name of the generated enum containing all colors.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Note: if you use --param enumName=UIColor (or NSColor on macOS) then the color constants will be generated as an extension of the UIColor (iOS) / NSColor (macOS) type directly without creating a separate enum type for namespacing those color constants.

Generated Code

Extract:

swift
extension ColorName {
  /// 0x339666ff (r: 51, g: 150, b: 102, a: 255)
  static let articleBody = #colorLiteral(red: 0.2, green: 0.588235, blue: 0.4, alpha: 1.0)
  /// 0xff66ccff (r: 255, g: 102, b: 204, a: 255)
  static let articleFootnote = #colorLiteral(red: 1.0, green: 0.4, blue: 0.8, alpha: 1.0)
}

Full generated code

Usage example

swift
// To reference a color, simpy reference its static instance by name:
let title = ColorName.articleBody
let footnote = ColorName.articleFootnote

Documentation Colors Swift2 (`Documentation/colors/swift2.md`)

Template Information

Name Description
File name colors/swift2.stencil
Invocation example swiftgen colors -t swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • Supports multiple color names with the same value
  • Warning: Swift 2 is no longer actively supported, so we cannot guarantee that there won't be issues with the generated code.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName ColorName Allows you to change the name of the generated enum containing all colors.
colorAliasName Color Allows you to change the name of the generated typealias for the platform specific color type.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
}

Full generated code

Usage example

swift
// You can create colors with the convenience constructor like this:
let title = UIColor(named: .ArticleBody)
let footnote = UIColor(named: .ArticleFootnote)

// 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

Documentation Colors Swift3 (`Documentation/colors/swift3.md`)

Template Information

Name Description
File name colors/swift3.stencil
Invocation example swiftgen colors -t swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code
  • Supports multiple color names with the same value

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName ColorName Allows you to change the name of the generated enum containing all colors.
colorAliasName Color Allows you to change the name of the generated typealias for the platform specific color type.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
}

Full generated code

Usage example

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

// 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

Documentation Colors Swift4 (`Documentation/colors/swift4.md`)

Template Information

Name Description
File name colors/swift4.stencil
Invocation example swiftgen colors -t swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code
  • Supports multiple color names with the same value

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName ColorName Allows you to change the name of the generated enum containing all colors.
colorAliasName Color Allows you to change the name of the generated typealias for the platform specific color type.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
}

Full generated code

Usage example

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

// 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

Documentation Fonts Swift2 (`Documentation/fonts/swift2.md`)

Template Information

Name Description
File name fonts/swift2.stencil
Invocation example swiftgen fonts -t swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • Warning: Swift 2 is no longer actively supported, so we cannot guarantee that there won't be issues with the generated code.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName FontFamily Allows you to change the name of the generated enum containing all font families.
preservePath N/A Setting this parameter will disable the basename filter applied to all font paths. Use this if you added your font folder as a "folder reference" in your Xcode project, making that folder hierarchy preserved once copied in the build app bundle. The path will be relative to the folder you provided to SwiftGen.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum FontFamily {
  enum SFNSDisplay {
    static let Black = FontConvertible(".SFNSDisplay-Black", family: ".SF NS Display", path: "SFNSDisplay-Black.otf")
    static let Bold = FontConvertible(".SFNSDisplay-Bold", family: ".SF NS Display", path: "SFNSDisplay-Bold.otf")
    static let Heavy = FontConvertible(".SFNSDisplay-Heavy", family: ".SF NS Display", path: "SFNSDisplay-Heavy.otf")
    static let Regular = FontConvertible(".SFNSDisplay-Regular", family: ".SF NS Display", path: "SFNSDisplay-Regular.otf")
  }
  enum ZapfDingbats {
    static let Regular = FontConvertible("ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")
  }
}

Full generated code

Usage example

swift
// You can create fonts with the convenience constructor like this:
let displayRegular = UIFont(FontFamily.SFNSDisplay.Regular, size: 20.0)
let dingbats = UIFont(FontFamily.ZapfDingbats.Regular, size: 20.0)

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

Documentation Fonts Swift3 (`Documentation/fonts/swift3.md`)

Template Information

Name Description
File name fonts/swift3.stencil
Invocation example swiftgen fonts -t swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName FontFamily Allows you to change the name of the generated enum containing all font families.
preservePath N/A Setting this parameter will disable the basename filter applied to all font paths. Use this if you added your font folder as a "folder reference" in your Xcode project, making that folder hierarchy preserved once copied in the build app bundle. The path will be relative to the folder you provided to SwiftGen.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum FontFamily {
  enum SFNSDisplay {
    static let black = FontConvertible(name: ".SFNSDisplay-Black", family: ".SF NS Display", path: "SFNSDisplay-Black.otf")
    static let bold = FontConvertible(name: ".SFNSDisplay-Bold", family: ".SF NS Display", path: "SFNSDisplay-Bold.otf")
    static let heavy = FontConvertible(name: ".SFNSDisplay-Heavy", family: ".SF NS Display", path: "SFNSDisplay-Heavy.otf")
    static let regular = FontConvertible(name: ".SFNSDisplay-Regular", family: ".SF NS Display", path: "SFNSDisplay-Regular.otf")
  }
  enum ZapfDingbats {
    static let regular = FontConvertible(name: "ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")
  }
}

Full generated code

Usage example

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

// 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)

Documentation Fonts Swift4 (`Documentation/fonts/swift4.md`)

Template Information

Name Description
File name fonts/swift4.stencil
Invocation example swiftgen fonts -t swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName FontFamily Allows you to change the name of the generated enum containing all font families.
preservePath N/A Setting this parameter will disable the basename filter applied to all font paths. Use this if you added your font folder as a "folder reference" in your Xcode project, making that folder hierarchy preserved once copied in the build app bundle. The path will be relative to the folder you provided to SwiftGen.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum FontFamily {
  enum SFNSDisplay {
    static let black = FontConvertible(name: ".SFNSDisplay-Black", family: ".SF NS Display", path: "SFNSDisplay-Black.otf")
    static let bold = FontConvertible(name: ".SFNSDisplay-Bold", family: ".SF NS Display", path: "SFNSDisplay-Bold.otf")
    static let heavy = FontConvertible(name: ".SFNSDisplay-Heavy", family: ".SF NS Display", path: "SFNSDisplay-Heavy.otf")
    static let regular = FontConvertible(name: ".SFNSDisplay-Regular", family: ".SF NS Display", path: "SFNSDisplay-Regular.otf")
  }
  enum ZapfDingbats {
    static let regular = FontConvertible(name: "ZapfDingbatsITC", family: "Zapf Dingbats", path: "ZapfDingbats.ttf")
  }
}

Full generated code

Usage example

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

// 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)

Documentation Storyboards Swift2 (`Documentation/storyboards/swift2.md`)

Template Information

Name Description
File name storyboards/swift2.stencil
Invocation example swiftgen storyboards -t swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • The generated code supports both UIKit platforms (iOS, tvOS and watchOS) and AppKit platform (macOS)
  • Warning: Swift 2 is no longer actively supported, so we won't maintain this template and don't unit-test the generated code for it anymore.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
sceneEnumName StoryboardScene Allows you to change the name of the generated enum containing all storyboard scenes.
segueEnumName StoryboardSegue Allows you to change the name of the generated enum containing all storyboard segues.
module N/A By default, the template will import the needed modules for custom classes, but wonโ€™t import the targetโ€™s module to avoid an import warning โ€” using the PRODUCT_MODULE_NAME environment variable to detect it. Should you need to ignore an additional module, you can provide it here.
ignoreTargetModule N/A Setting this parameter will disable the behaviour of prefixing classes with their module name for (only) the target module.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Note: the generated code may look differently depending on the platform the storyboard file is targeting.

Extract:

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

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

    static let MessagesList = SceneType<UITableViewController>(Message.self, identifier: "MessagesList")
  }
}
enum StoryboardSegue {
  enum Message: String, SegueType {
    case Embed
    case NonCustom
  }
}

Full generated code

Usage example

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

// You can perform segues using:
vc.performSegue(StoryboardSegue.Message.Embed)

// or match them (in prepareForSegue):
override func prepareForSegue(_ segue: UIStoryboardSegue, sender sender: AnyObject?) {
  switch StoryboardSegue.Message(rawValue: segue.identifier!)! {
  case .Embed:
    // Prepare for your custom segue transition
  case .NonCustom:
    // Pass in information to the destination View Controller
  }
}

Documentation Storyboards Swift3 (`Documentation/storyboards/swift3.md`)

Template Information

Name Description
File name storyboards/swift3.stencil
Invocation example swiftgen storyboards -t swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code
  • The generated code supports both UIKit platforms (iOS, tvOS and watchOS) and AppKit platform (macOS)

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
sceneEnumName StoryboardScene Allows you to change the name of the generated enum containing all storyboard scenes.
segueEnumName StoryboardSegue Allows you to change the name of the generated enum containing all storyboard segues.
module N/A By default, the template will import the needed modules for custom classes, but wonโ€™t import the targetโ€™s module to avoid an import warning โ€” using the PRODUCT_MODULE_NAME environment variable to detect it. Should you need to ignore an additional module, you can provide it here.
ignoreTargetModule N/A Setting this parameter will disable the behaviour of prefixing classes with their module name for (only) the target module.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Note: the generated code may look differently depending on the platform the storyboard file is targeting.

Extract:

swift
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")
  }
}
enum StoryboardSegue {
  enum Message: String, SegueType {
    case embed
    case nonCustom
  }
}

Full generated code

Usage example

swift
// 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(rawValue: segue.identifier!)! {
  case .embed:
    // Prepare for your custom segue transition
  case .nonCustom:
    // Pass in information to the destination View Controller
  }
}

Documentation Storyboards Swift4 (`Documentation/storyboards/swift4.md`)

Template Information

Name Description
File name storyboards/swift4.stencil
Invocation example swiftgen storyboards -t swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code
  • The generated code supports both UIKit platforms (iOS, tvOS and watchOS) and AppKit platform (macOS)

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
sceneEnumName StoryboardScene Allows you to change the name of the generated enum containing all storyboard scenes.
segueEnumName StoryboardSegue Allows you to change the name of the generated enum containing all storyboard segues.
module N/A By default, the template will import the needed modules for custom classes, but wonโ€™t import the targetโ€™s module to avoid an import warning โ€” using the PRODUCT_MODULE_NAME environment variable to detect it. Should you need to ignore an additional module, you can provide it here.
ignoreTargetModule N/A Setting this parameter will disable the behaviour of prefixing classes with their module name for (only) the target module.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Note: the generated code may look differently depending on the platform the storyboard file is targeting.

Extract:

swift
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")
  }
}
enum StoryboardSegue {
  enum Message: String, SegueType {
    case embed
    case nonCustom
  }
}

Full generated code

Usage example

swift
// 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(rawValue: segue.identifier!)! {
  case .embed:
    // Prepare for your custom segue transition
  case .nonCustom:
    // Pass in information to the destination View Controller
  }
}

Documentation Strings Flat Swift2 (`Documentation/strings/flat-swift2.md`)

Template Information

Name Description
File name strings/flat-swift2.stencil
Invocation example swiftgen strings -t flat-swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • If you use unstructured key names for your strings, or a structure that we don't support (yet). If you use "dot-syntax" keys, please check out the structured-swift2 template.
  • Warning: Swift 2 is no longer actively supported, so we cannot guarantee that there won't be issues with the generated code.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
}

Full generated code

Usage example

swift
// 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")

Documentation Strings Flat Swift3 (`Documentation/strings/flat-swift3.md`)

Template Information

Name Description
File name strings/flat-swift3.stencil
Invocation example swiftgen strings -t flat-swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code
  • If you use unstructured key names for your strings, or a structure that we don't support (yet). If you use "dot-syntax" keys, please check out the structured-swift3 template.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum L10n {
  /// Some alert body there
  static let alertMessage = L10n.tr("Localizable", "alert_message")
  /// Title of the alert
  static let alertTitle = L10n.tr("Localizable", "alert_title")
  /// You have %d apples
  static func applesCount(_ p1: Int) -> String {
    return L10n.tr("Localizable", "apples.count", p1)
  }
  /// Those %d bananas belong to %@.
  static func bananasOwner(_ p1: Int, _ p2: String) -> String {
    return L10n.tr("Localizable", "bananas.owner", p1, p2)
  }

Full generated code

Usage example

swift
// 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")

Documentation Strings Flat Swift4 (`Documentation/strings/flat-swift4.md`)

Template Information

Name Description
File name strings/flat-swift4.stencil
Invocation example swiftgen strings -t flat-swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code
  • If you use unstructured key names for your strings, or a structure that we don't support (yet). If you use "dot-syntax" keys, please check out the structured-swift4 template.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
}

Full generated code

Usage example

swift
// 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")

Documentation Strings Structured Swift2 (`Documentation/strings/structured-swift2.md`)

Template Information

Name Description
File name strings/structured-swift2.stencil
Invocation example swiftgen strings -t structured-swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • If you use "structured" keys for your strings, that is components separated by the . character, for example:
text
"some.deep.structure"
"some.deep.something"
"hello.world"
  • Warning: Swift 2 is no longer actively supported, so we cannot guarantee that there won't be issues with the generated code.

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
    }
  }
}

Full generated code

Usage example

swift
// 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")

Documentation Strings Structured Swift3 (`Documentation/strings/structured-swift3.md`)

Template Information

Name Description
File name strings/structured-swift3.stencil
Invocation example swiftgen strings -t structured-swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code
  • If you use "structured" keys for your strings, that is components separated by the . character, for example:
text
"some.deep.structure"
"some.deep.something"
"hello.world"

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
    }
  }
}

Full generated code

Usage example

swift
// 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")

Documentation Strings Structured Swift4 (`Documentation/strings/structured-swift4.md`)

Template Information

Name Description
File name strings/structured-swift4.stencil
Invocation example swiftgen strings -t structured-swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code
  • If you use "structured" keys for your strings, that is components separated by the . character, for example:
text
"some.deep.structure"
"some.deep.something"
"hello.world"

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName L10n Allows you to change the name of the generated enum containing all string tables.
noComments N/A Setting this parameter will disable the comments describing the translation of a key.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
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)
    }
  }
}

Full generated code

Usage example

swift
// 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")

Documentation Xcassets Swift2 (`Documentation/xcassets/swift2.md`)

Template Information

Name Description
File name xcassets/swift2.stencil
Invocation example swiftgen xcassets -t swift2 โ€ฆ
Language Swift 2
Author Olivier Halligon

When to use it

  • When you need to generate Swift 2 code
  • Warning: Swift 2 is no longer actively supported, so we cannot guarantee that there won't be issues with the generated code.

It also takes into account any namespacing folder in your Assets Catalogs (i.e. if you create a folder in your Assets Catalog, select it, and check the "Provides Namespace" checkbox on the Attributes Inspector panel on the right)

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName Asset Allows you to change the name of the generated enum containing all assets.
imageAliasName Image Allows you to change the name of the generated typealias for the platform specific image type.
colorTypeName ColorAsset Allows you to change the name of the struct type representing a color.
imageTypeName ImageAsset Allows you to change the name of the struct type representing an image.
noAllValues N/A Setting this parameter will disable generation of the allColors and allImages constants.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum Asset {
  enum Exotic {
    static let Banana = ImageAsset(value: "Exotic/Banana")
    static let Mango = ImageAsset(value: "Exotic/Mango")
  }
  static let Private = ImageAsset(value: "private")
  enum Theme {
  	static let Primary = ColorAsset(value: "Theme/Primary")
  	static let Background = ColorAsset(value: "Theme/Background")
  }
}

Full generated code

Usage example

swift
// You can create new images by referring to the enum instance and calling `.image` on it:
let bananaImage = Asset.Exotic.Banana.image
let privateImage = Asset.Private.image

// Or as an alternative, you use the convenience constructor like this:
let sameBananaImage = UIImage(asset: Asset.Exotic.Banana)
let samePrivateImage = UIImage(asset: Asset.Private)

Note: This swift 2 template does not support named colors. To use those, you'll need to use a more recent swift version.


Documentation Xcassets Swift3 (`Documentation/xcassets/swift3.md`)

Template Information

Name Description
File name xcassets/swift3.stencil
Invocation example swiftgen xcassets -t swift3 โ€ฆ
Language Swift 3
Author Olivier Halligon

When to use it

  • When you need to generate Swift 3 code

It also takes into account any namespacing folder in your Assets Catalogs (i.e. if you create a folder in your Assets Catalog, select it, and check the "Provides Namespace" checkbox on the Attributes Inspector panel on the right)

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName Asset Allows you to change the name of the generated enum containing all assets.
colorAliasName AssetColorTypeAlias Allows you to change the name of the generated typealias for the platform specific color type.
imageAliasName Image Allows you to change the name of the generated typealias for the platform specific image type.
colorTypeName ColorAsset Allows you to change the name of the struct type representing a color.
imageTypeName ImageAsset Allows you to change the name of the struct type representing an image.
noAllValues N/A Setting this parameter will disable generation of the allColors and allImages constants.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum Asset {
  enum Exotic {
    static let banana = ImageAsset(value: "Exotic/Banana")
    static let mango = ImageAsset(value: "Exotic/Mango")
  }
  static let `private` = ImageAsset(value: "private")
  enum Theme {
  	static let primary = ColorAsset(value: "Theme/Primary")
  	static let background = ColorAsset(value: "Theme/Background")
  }
}

Full generated code

Usage example

swift
// You can create new images by referring to the enum instance and calling `.image` on it:
let bananaImage = Asset.Exotic.banana.image
let privateImage = Asset.private.image

// Or as an alternative, you use the convenience constructor like this:
let sameBananaImage = UIImage(asset: Asset.Exotic.banana)
let samePrivateImage = UIImage(asset: Asset.private)

// similarly, you can create colors by referring to the enum instance and calling `.color` on it:
let primaryColor = Asset.Theme.primary.color
let backgroundColor = Asset.Theme.background.color

// Or as an alternative, you use the convenience constructor like this:
let samePrimaryColor = UIColor(asset: Asset.Theme.primary)
let sameBackgroundColor = UIColor(asset: Asset.Theme.background)

Documentation Xcassets Swift4 (`Documentation/xcassets/swift4.md`)

Template Information

Name Description
File name xcassets/swift4.stencil
Invocation example swiftgen xcassets -t swift4 โ€ฆ
Language Swift 4
Author Olivier Halligon

When to use it

  • When you need to generate Swift 4 code

It also takes into account any namespacing folder in your Assets Catalogs (i.e. if you create a folder in your Assets Catalog, select it, and check the "Provides Namespace" checkbox on the Attributes Inspector panel on the right)

Customization

You can customize some elements of this template by overriding the following parameters when invoking swiftgen in the command line, using --param =<newValue>

Parameter Name Default Value Description
enumName Asset Allows you to change the name of the generated enum containing all assets.
colorAliasName AssetColorTypeAlias Allows you to change the name of the generated typealias for the platform specific color type.
imageAliasName Image Allows you to change the name of the generated typealias for the platform specific image type.
colorTypeName ColorAsset Allows you to change the name of the struct type representing a color.
imageTypeName ImageAsset Allows you to change the name of the struct type representing an image.
noAllValues N/A Setting this parameter will disable generation of the allColors and allImages constants.
publicAccess N/A If set, the generated constants will be marked as public. Otherwise, they'll be declared internal.

Generated Code

Extract:

swift
enum Asset {
  enum Exotic {
    static let banana = ImageAsset(value: "Exotic/Banana")
    static let mango = ImageAsset(value: "Exotic/Mango")
  }
  static let `private` = ImageAsset(value: "private")
  enum Theme {
  	static let primary = ColorAsset(value: "Theme/Primary")
  	static let background = ColorAsset(value: "Theme/Background")
  }
}

Full generated code

Usage example

swift
// You can create new images by referring to the enum instance and calling `.image` on it:
let bananaImage = Asset.Exotic.banana.image
let privateImage = Asset.private.image

// Or as an alternative, you use the convenience constructor like this:
let sameBananaImage = UIImage(asset: Asset.Exotic.banana)
let samePrivateImage = UIImage(asset: Asset.private)

// similarly, you can create colors by referring to the enum instance and calling `.color` on it:
let primaryColor = Asset.Theme.primary.color
let backgroundColor = Asset.Theme.background.color

// Or as an alternative, you use the convenience constructor like this:
let samePrimaryColor = UIColor(asset: Asset.Theme.primary)
let sameBackgroundColor = UIColor(asset: Asset.Theme.background)

--- METRICS ---