{"id":26707988,"url":"https://github.com/AliSoftware/SwiftGen","last_synced_at":"2025-03-27T07:02:01.923Z","repository":{"id":35043377,"uuid":"39166950","full_name":"SwiftGen/SwiftGen","owner":"SwiftGen","description":"The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!","archived":false,"fork":false,"pushed_at":"2024-07-19T15:53:13.000Z","size":49775,"stargazers_count":9265,"open_issues_count":143,"forks_count":737,"subscribers_count":101,"default_branch":"stable","last_synced_at":"2024-10-29T11:23:33.574Z","etag":null,"topics":["code-generator","ios","localization","stencil","stencil-template","swift","templates","uicolor","uifont","uiimage","uistoryboard"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"lauripiispanen/heroku-buildpack-ghostscript","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SwiftGen.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-07-15T23:58:44.000Z","updated_at":"2024-10-28T05:55:37.000Z","dependencies_parsed_at":"2024-10-29T11:32:21.544Z","dependency_job_id":null,"html_url":"https://github.com/SwiftGen/SwiftGen","commit_stats":{"total_commits":2288,"total_committers":117,"mean_commits":"19.555555555555557","dds":0.6127622377622377,"last_synced_commit":"1cf6d7eebd70c2157f69d5a991bc57c1ef182ed1"},"previous_names":["alisoftware/swiftgen"],"tags_count":58,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftGen%2FSwiftGen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftGen%2FSwiftGen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftGen%2FSwiftGen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SwiftGen%2FSwiftGen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SwiftGen","download_url":"https://codeload.github.com/SwiftGen/SwiftGen/tar.gz/refs/heads/stable","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245798587,"owners_count":20673902,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code-generator","ios","localization","stencil","stencil-template","swift","templates","uicolor","uifont","uiimage","uistoryboard"],"created_at":"2025-03-27T07:01:58.999Z","updated_at":"2025-03-27T07:02:01.902Z","avatar_url":"https://github.com/SwiftGen.png","language":"Swift","readme":"# SwiftGen\n\n[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/SwiftGen.svg)](https://img.shields.io/cocoapods/v/SwiftGen.svg)\n[![Platform](https://img.shields.io/cocoapods/p/SwiftGen.svg?style=flat)](http://cocoadocs.org/docsets/SwiftGen)\n![Swift 4.x](https://img.shields.io/badge/Swift-4.x-orange) ![Swift 5.x](https://img.shields.io/badge/Swift-5.x-orange)\n\nSwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.\n\n\u003ctable border=\"0\"\u003e\u003ctr\u003e\n  \u003ctd\u003e\n    \u003cimg alt=\"SwiftGen Logo\" src=\"https://github.com/SwiftGen/Eve/raw/master/logo/logo-256.png\" /\u003e\n  \u003c/td\u003e\u003ctd\u003e\n    \u003cul\u003e\n        \u003cli\u003e\u003ca href=\"#installation\"\u003eInstallation\u003c/a\u003e\n        \u003cli\u003e\u003ca href=\"#configuration-file\"\u003eConfiguration File\u003c/a\u003e\n        \u003cli\u003e\u003ca href=\"#choosing-your-template\"\u003eChoosing your template\u003c/a\u003e\n        \u003cli\u003e\u003ca href=\"#additional-documentation\"\u003eAdditional documentation\u003c/a\u003e\n    \u003c/ul\u003e\n    Then generate constants for:\n    \u003cul\u003e\n      \u003cli\u003e\u003ca href=\"#asset-catalog\"\u003eAssets Catalogs\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#colors\"\u003eColors\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#core-data\"\u003eCore Data\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#files\"\u003eFiles\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#fonts\"\u003eFonts\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#interface-builder\"\u003eInterface Builder files\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#json-and-yaml\"\u003eJSON and YAML files\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#plists\"\u003ePlists\u003c/a\u003e\n      \u003cli\u003e\u003ca href=\"#strings\"\u003eLocalizable strings\u003c/a\u003e\n    \u003c/ul\u003e\n  \u003c/td\u003e\n\u003c/tr\u003e\u003c/table\u003e\n\n\u003cspan style=\"float:none\" /\u003e\n\nThere are multiple benefits in using this:\n\n* Avoid any risk of typo when using a String\n* Free auto-completion\n* Avoid the risk of using a non-existing asset name\n* All this will be ensured by the compiler and thus avoid the risk of crashing at runtime.\n\nAlso, 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!\n\n## Installation\n\nThere are multiple possibilities to install SwiftGen on your machine or in your project, depending on your preferences and needs:\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eDownload the ZIP\u003c/strong\u003e for the latest release\u003c/summary\u003e\n\n* [Go to the GitHub page for the latest release](https://github.com/SwiftGen/SwiftGen/releases/latest)\n* Download the `swiftgen-x.y.z.zip` file associated with that release\n* Extract the content of the zip archive in your project directory\n\nWe 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**.\n\nIf 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:\n\n```sh\n\"${PROJECT_DIR}/swiftgen/bin/swiftgen\" …\n```\n\n---\n\u003c/details\u003e\n\u003cdetails\u003e\n\u003csummary\u003eVia \u003cstrong\u003eCocoaPods\u003c/strong\u003e\u003c/summary\u003e\n\nIf you're using CocoaPods, simply add `pod 'SwiftGen', '~\u003e 6.0'` to your `Podfile`.\n\nThen 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.\n\nGiven 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**.\n\nYou can then invoke SwiftGen in your Script Build Phase using:\n\n```sh\nif [[ -f \"${PODS_ROOT}/SwiftGen/bin/swiftgen\" ]]; then\n  \"${PODS_ROOT}/SwiftGen/bin/swiftgen\" …\nelse\n  echo \"warning: SwiftGen is not installed. Run 'pod install --repo-update' to install it.\"\nfi\n```\n\n\u003e 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.\n\n_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._\n\n---\n\u003c/details\u003e\n\u003cdetails\u003e\n\u003csummary\u003eVia \u003cstrong\u003eHomebrew\u003c/strong\u003e \u003cem\u003e(system-wide installation)\u003c/em\u003e\u003c/summary\u003e\n\nTo install SwiftGen via [Homebrew](http://brew.sh), simply use:\n\n```sh\n$ brew update\n$ brew install swiftgen\n```\n\nThis 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.\n\nYou can then invoke `swiftgen` directly in your Script Build Phase (as it will be in your `$PATH` already):\n\n```sh\nswiftgen … \n```\n\n---\n\u003c/details\u003e\n\u003cdetails\u003e\n\u003csummary\u003eVia \u003cstrong\u003eMint\u003c/strong\u003e \u003cem\u003e(system-wide installation)\u003c/em\u003e\u003c/summary\u003e\n\n\u003e ❗️SwiftGen 6.0 or higher only.\n\nTo install SwiftGen via [Mint](https://github.com/yonaskolb/Mint), simply use:\n\n```sh\n$ mint install SwiftGen/SwiftGen\n```\n---\n\u003c/details\u003e\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eCompile from source\u003c/strong\u003e \u003cem\u003e(only recommended if you need features from the `stable` branch or want to test a PR)\u003c/em\u003e\u003c/summary\u003e\n\nThis solution is when you want to build and install the latest version from `stable` and have access to features which might not have been released yet.\n\n* If you have `homebrew` installed, you can use the following command to build and install the latest commit:\n\n```sh\nbrew install swiftgen --HEAD\n```\n\n* 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.\n\nSome 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.  \n\nThen install the Ruby Gems:\n\n```sh\n# Install bundle if it isn't installed\ngem install bundle\n# Install the Ruby gems from Gemfile\nbundle install\n```\n\nYou can now install to the default locations (no parameter) or to custom locations:\n\n```sh\n# Binary is installed in `./.build/swiftgen/bin`\n$ rake cli:install\n# - OR -\n# Binary will be installed in `~/swiftgen/bin``\n$ rake cli:install[~/swiftgen/bin]\n```\n\nYou can then invoke SwiftGen using the path to the binary where you installed it:\n\n```sh\n~/swiftgen/bin/swiftgen …\n```\n\nOr add the path to the `bin` folder to your `$PATH` and invoke `swiftgen` directly.\n\n---\n\u003c/details\u003e\n\n### Known Installation Issues On macOS Before 10.14.4\n\nStarting with [SwiftGen 6.2.1](https://github.com/SwiftGen/SwiftGen/releases/6.2.1), if you get an error similar to `dyld: Symbol not found: _$s11SubSequenceSlTl` when running SwiftGen, you'll need to install the [Swift 5 Runtime Support for Command Line Tools](https://support.apple.com/kb/DL1998).\n\nAlternatively, you can:\n\n- Update to macOS 10.14.4 or later\n- Install Xcode 10.2 or later at `/Applications/Xcode.app`\n- Rebuild SwiftGen from source using Xcode 10.2 or later\n\n## Configuration File\n\n\u003e ❗️ If you're migrating from older SwiftGen versions, don't forget to [read the Migration Guide](Documentation/MigrationGuide.md).\n\nSwiftGen is provided as a single command-line tool which uses a configuration file to define the various parsers to run (depending on the type of input files you need to parse) and their parameters.\n\nTo create a sample configuration file as a starting point to adapt to your needs, run `swiftgen config init`.\n\nEach parser described in the [configuration file](Documentation/ConfigFile.md) (`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.\n\nTo use SwiftGen, simply create a `swiftgen.yml` YAML file (either manually or using `swiftgen config init`) then edit it to adapt to your project. The config file should list all the parsers to invoke, and for each parser, the list of inputs/outputs/templates/parameters to use for it.\n\nFor example:\n\n```yaml\nstrings:\n  inputs: Resources/Base.lproj\n  outputs:\n    - templateName: structured-swift5\n      output: Generated/Strings.swift\nxcassets:\n  inputs:\n    - Resources/Images.xcassets\n    - Resources/MoreImages.xcassets\n    - Resources/Colors.xcassets\n  outputs:\n    - templateName: swift5\n      output: Generated/Assets.swift\n```\n\nThen 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.\n\n[The dedicated documentation](Documentation/ConfigFile.md) explains the syntax and possibilities in details – like how to pass custom parameters to your templates, use `swiftgen config lint` to validate your config file, how to use alternate config files, and other tips.\n\nThere are also additional subcommands you can invoke from the command line to manage and configure SwiftGen:\n\n* The `swiftgen config` subcommand to help you with the configuration file, especially `swiftgen config init` to create a starting point for your config and `swiftgen config lint` to validate that your Config file is valid and has no errors\n* The `swiftgen template` subcommands to help you print, duplicate, find and manage templates bundled with SwiftGen\n\nLastly, you can use `--help` on `swiftgen` or one of its subcommand to see the detailed usage.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eDirectly invoking a parser without a config file\u003c/strong\u003e\u003c/summary\u003e\n\nWhile 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 parsers individually using `swiftgen run`:\n\n* `swiftgen run colors [OPTIONS] DIRORFILE1 …`\n* `swiftgen run coredata [OPTIONS] DIRORFILE1 …`\n* `swiftgen run files [OPTIONS] DIRORFILE1 …`\n* `swiftgen run fonts [OPTIONS] DIRORFILE1 …`\n* `swiftgen run ib [OPTIONS] DIRORFILE1 …`\n* `swiftgen run json [OPTIONS] DIRORFILE1 …`\n* `swiftgen run plist [OPTIONS] DIRORFILE1 …`\n* `swiftgen run strings [OPTIONS] DIRORFILE1 …`\n* `swiftgen run xcassets [OPTIONS] DIRORFILE1 …`\n* `swiftgen run yaml [OPTIONS] DIRORFILE1 …`\n\nOne 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 parser you're working on at each iteration/version of your custom template, until you're happy with it.\n\nEach parser command generally accepts the same options and syntax, and they mirror the options and parameters from the configuration file:\n\n* `--output FILE` or `-o FILE`: set the file where to write the generated code. If omitted, the generated code will be printed on `stdout`.\n* `--templateName NAME` or `-n NAME`: define the Stencil template to use (by name, see [here for more info](Documentation/templates)) to generate the output.\n* `--templatePath PATH` or `-p PATH`: define the Stencil template to use, using a full path.\n* 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)\n* `--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.\n* 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](https://regexr.com) to ensure you're using a valid regular expression.\n* Each command supports multiple input files (or directories where applicable).\n* You can always use the `--help` flag to see what options a command accept, e.g. `swiftgen run xcassets --help`.\n\n\u003c/details\u003e\n\n## Choosing your template\n\nSwiftGen is based on templates (it uses [Stencil](https://github.com/stencilproject/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**.\n\n### Bundled templates vs. Custom ones\n\nSwiftGen comes bundled with some templates for each of the parsers (`colors`, `coredata`, `files`, `fonts`, `ib`, `json`, `plist`, `strings`, `xcassets`, `yaml`), which will fit most needs; simply use the `templateName` output option to specify the name of the template to use. But you can also create your own templates if the bundled ones don't suit your coding conventions or needs: just store them anywhere (like in your project repository) and use the `templatePath` output option instead of `templateName`, to specify their path.\n\n💡 You can use the `swiftgen template list` command to list all the available bundled templates for each parser, and use `swiftgen template cat` to show a template's content and duplicate it to create your own variation.\n\nFor more information about how to create your own templates, [see the dedicated documentation](Documentation/Articles/Creating-custom-templates.md).\n\n### Templates bundled with SwiftGen:\n\nAs explained above, you can use `swiftgen template list` to list all templates bundled with SwiftGen. For most SwiftGen parsers, we provide, among others:\n\n* A `swift4` template, compatible with Swift 4\n* A `swift5` template, compatible with Swift 5\n* Other variants, like `flat-swift4/5` and `structured-swift4/5` templates for Strings, etc.\n\nYou can **find the documentation for each bundled template [here in the repo](Documentation/templates)**, with documentation organized as one folder per SwiftGen parser, then one MarkDown file per template. You can also use `swiftgen template doc` to open that documentation page in your browser directly from your terminal.\n\nEach 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.\n\n\u003e Don't hesitate to make PRs to share your improvements suggestions on the bundled templates 😉\n\n## Additional documentation\n\n### Playground\n\nThe `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.\n\nThis 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.\n\n### Dedicated Documentation in Markdown\n\nThere is a lot of documentation in the form of Markdown files in this repository, and in the related [StencilSwiftKit](https://github.com/SwiftGen/StencilSwiftKit) repository as well.\n\nBe sure to [check the \"Documentation\" folder](Documentation/) of each repository.\n\nEspecially, in addition to the previously mentioned [Migration Guide](Documentation/MigrationGuide.md) and [Configuration File](Documentation/ConfigFile.md) documentation, the `Documentation/` folder in the SwiftGen repository also includes:\n\n* A [`templates` subdirectory](Documentation/templates/) that details the documentation for each of the templates bundled with SwiftGen (when to use each template, what the output will look like, and custom parameters to adjust them, …)\n* A [`SwiftGenKit Contexts` subdirectory](Documentation/SwiftGenKit%20Contexts/) that details the structure of the \"Stencil Contexts\", i.e. the Dictionary/YAML representation resulting of parsing your input files. This documentation is useful for people wanting to write their own templates, so that they know the structure and various keys available when writing their template, to construct the wanted generated output accordingly.\n* [Various articles](Documentation/Articles/) to provide best practices \u0026 tips on how to better take advantage of SwiftGen in your projects:\n  * [Integrate SwiftGen in your Xcode project](Documentation/Articles/Xcode-Integration.md) — so it rebuilds the constants every time you build\n  * [Configure SwiftLint to help your developers use constants generated by SwiftGen](Documentation/Articles/SwiftLint-Integration.md)\n  * [Create a custom template](Documentation/Articles/Creating-custom-templates.md), and [watch a folder to auto-regenerate an output every time you save the template you're working on](Documentation/Articles/Watch-a-folder-for-changes.md)\n  * …and more\n\n### Tutorials\n\nYou can also find other help \u0026 tutorial material on the internet, like [this classroom about Code Generation I gave at FrenchKit in Sept'17](https://github.com/FrenchKit/Mastering-code-generation-Classroom) — and its wiki detailing a step-by-step tutorial about installing and using SwiftGen (and Sourcery too)\n\n---\n\n# Available Parsers\n\n## Asset Catalog\n\n```yaml\nxcassets:\n  inputs: /dir/to/search/for/imageset/assets\n  outputs:\n    templateName: swift5\n    output: Assets.swift\n```\n\nThis will generate an `enum Asset` with one `static let` per asset (image set, color set, data set, …) in your assets catalog, so that you can use them as constants.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal enum Asset {\n  internal enum Files {\n    internal static let data = DataAsset(value: \"Data\")\n    internal static let readme = DataAsset(value: \"README\")\n  }\n  internal enum Food {\n    internal enum Exotic {\n      internal static let banana = ImageAsset(value: \"Exotic/Banana\")\n      internal static let mango = ImageAsset(value: \"Exotic/Mango\")\n    }\n    internal static let `private` = ImageAsset(value: \"private\")\n  }\n  internal enum Styles {\n    internal enum Vengo {\n      internal static let primary = ColorAsset(value: \"Vengo/Primary\")\n      internal static let tint = ColorAsset(value: \"Vengo/Tint\")\n    }\n  }\n  internal enum Symbols {\n    internal static let exclamationMark = SymbolAsset(name: \"Exclamation Mark\")\n    internal static let plus = SymbolAsset(name: \"Plus\")\n  }\n  internal enum Targets {\n    internal static let bottles = ARResourceGroupAsset(name: \"Bottles\")\n    internal static let paintings = ARResourceGroupAsset(name: \"Paintings\")\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// You can create new images by referring to the enum instance and calling `.image` on it:\nlet bananaImage = Asset.Exotic.banana.image\nlet privateImage = Asset.private.image\n\n// You can create colors by referring to the enum instance and calling `.color` on it:\nlet primaryColor = Asset.Styles.Vengo.primary.color\nlet tintColor = Asset.Styles.Vengo.tint.color\n\n// You can create data items by referring to the enum instance and calling `.data` on it:\nlet data = Asset.data.data\nlet readme = Asset.readme.data\n\n// You can load an AR resource group's items using:\nlet bottles = Asset.Targets.bottles.referenceObjects\nlet paintings = Asset.Targets.paintings.referenceImages\n\n// You can create new symbol images by referring to the enum instance and calling `.image` on it (with or without configuration)\nlet plus = Asset.Symbols.plus.image\nlet style = UIImage.SymbolConfiguration(textStyle: .headline)\nlet styled = Asset.Symbols.exclamationMark.image(with: style)\n```\n\n## Colors\n\n\u003e ❗️ We recommend to define your colors in your Assets Catalogs and use the `xcassets` parser (see above) to generate color constants, instead of using this `colors` parser described below.  \n\u003e The `colors` parser below is mainly useful if you support older versions of iOS where colors can't be defined in Asset Catalogs, or if you want to use Android's `colors.xml` files as input.\n\n```yaml\ncolors:\n  inputs: /path/to/colors-file.txt\n  outputs:\n    templateName: swift5\n    output: Colors.swift\n```\n\nThis will generate a `enum ColorName` with one `static let` per color listed in the text file passed as argument.\n\nThe input file is expected to be either:\n\n* a [plain text file](Sources/TestUtils/Fixtures/Resources/Colors/extra.txt), 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.\n* a [JSON file](Sources/TestUtils/Fixtures/Resources/Colors/colors.json), representing a dictionary of names -\u003e values, each value being the hex representation of the color\n* a [XML file](Sources/TestUtils/Fixtures/Resources/Colors/colors.xml), expected to be the same format as the Android colors.xml files, containing tags `\u003ccolor name=\"AColorName\"\u003eAColorHexRepresentation\u003c/color\u003e`\n* a [`*.clr` file](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DrawColor/Concepts/AboutColorLists.html#//apple_ref/doc/uid/20000757-BAJHJEDI) used by Apple's Color Palettes.\n\nFor example you can use this command to generate colors from one of your system color lists:\n\n```yaml\ncolors:\n  inputs: ~/Library/Colors/MyColors.clr\n  outputs:\n    templateName: swift5\n    output: Colors.swift\n```\n\nGenerated code will look the same as if you'd use a text file.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\nGiven the following `colors.txt` file:\n\n```\nCyan-Color       : 0xff66ccff\nArticleTitle     : #33fe66\nArticleBody      : 339666\nArticleFootnote  : ff66ccff\nTranslucent      : ffffffcc\n```\n\nThe generated code will look like this:\n\n```swift\ninternal struct ColorName {\n  internal let rgbaValue: UInt32\n  internal var color: Color { return Color(named: self) }\n\n  /// \u003cspan style=\"display:block;width:3em;height:2em;border:1px solid black;background:#339666\"\u003e\u003c/span\u003e\n  /// Alpha: 100% \u003cbr/\u003e (0x339666ff)\n  internal static let articleBody = ColorName(rgbaValue: 0x339666ff)\n  /// \u003cspan style=\"display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc\"\u003e\u003c/span\u003e\n  /// Alpha: 100% \u003cbr/\u003e (0xff66ccff)\n  internal static let articleFootnote = ColorName(rgbaValue: 0xff66ccff)\n\n  ...\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// You can create colors with the convenience constructor like this:\nlet title = UIColor(named: .articleBody)  // iOS\nlet footnote = NSColor(named: .articleFootnote) // macOS\n\n// Or as an alternative, you can refer to enum instance and call .color on it:\nlet sameTitle = ColorName.articleBody.color\nlet sameFootnote = ColorName.articleFootnote.color\n```\n\nThis way, no need to enter the color red, green, blue, alpha values each time and create ugly constants in the global namespace for them.\n\n## Core Data\n\n```yaml\ncoredata:\n  inputs: /path/to/model.xcdatamodeld\n  outputs:\n    templateName: swift5\n    output: CoreData.swift\n```\n\nThis 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.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal class MainEntity: NSManagedObject {\n  internal class var entityName: String {\n    return \"MainEntity\"\n  }\n\n  internal class func entity(in managedObjectContext: NSManagedObjectContext) -\u003e NSEntityDescription? {\n    return NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext)\n  }\n\n  @nonobjc internal class func makeFetchRequest() -\u003e NSFetchRequest\u003cMainEntity\u003e {\n    return NSFetchRequest\u003cMainEntity\u003e(entityName: entityName)\n  }\n\n  @NSManaged internal var attributedString: NSAttributedString?\n  @NSManaged internal var binaryData: Data?\n  @NSManaged internal var boolean: Bool\n  @NSManaged internal var date: Date?\n  @NSManaged internal var float: Float\n  @NSManaged internal var int64: Int64\n  internal var integerEnum: IntegerEnum {\n    get {\n      let key = \"integerEnum\"\n      willAccessValue(forKey: key)\n      defer { didAccessValue(forKey: key) }\n\n      guard let value = primitiveValue(forKey: key) as? IntegerEnum.RawValue,\n        let result = IntegerEnum(rawValue: value) else {\n        fatalError(\"Could not convert value for key '\\(key)' to type 'IntegerEnum'\")\n      }\n      return result\n    }\n    set {\n      let key = \"integerEnum\"\n      willChangeValue(forKey: key)\n      defer { didChangeValue(forKey: key) }\n\n      setPrimitiveValue(newValue.rawValue, forKey: key)\n    }\n  }\n  @NSManaged internal var manyToMany: Set\u003cSecondaryEntity\u003e\n}\n\n// MARK: Relationship ManyToMany\n\nextension MainEntity {\n  @objc(addManyToManyObject:)\n  @NSManaged public func addToManyToMany(_ value: SecondaryEntity)\n\n  @objc(removeManyToManyObject:)\n  @NSManaged public func removeFromManyToMany(_ value: SecondaryEntity)\n\n  @objc(addManyToMany:)\n  @NSManaged public func addToManyToMany(_ values: Set\u003cSecondaryEntity\u003e)\n\n  @objc(removeManyToMany:)\n  @NSManaged public func removeFromManyToMany(_ values: Set\u003cSecondaryEntity\u003e)\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// Fetch all the instances of MainEntity\nlet request = MainEntity.makeFetchRequest()\nlet mainItems = try myContext.execute(request)\n\n// Type-safe relationships: `relatedItem` will be a `SecondaryEntity?` in this case\nlet relatedItem = myMainItem.manyToMany.first\n```\n\n## Files\n\n```yaml\nfiles:\n  inputs: path/to/search\n  filter: .+\\.mp4$\n  outputs:\n    templateName: structured-swift5\n    output: Files.swift\n```\n\nThe files parser is intended to just list the name and mimetype of the files and subdirectories in a given directory. This will recursively search the specified directory using the given filter (default `.*`), defining a `struct File` for each matching file, and an hierarchical enum representing the directory structure of files.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal enum Files {\n  /// test.txt\n  internal static let testTxt = File(name: \"test\", ext: \"txt\", path: \"\", mimeType: \"text/plain\")\n  /// subdir/\n  internal enum Subdir {\n    /// subdir/A Video With Spaces.mp4\n    internal static let aVideoWithSpacesMp4 = File(name: \"A Video With Spaces\", ext: \"mp4\", path: \"subdir\", mimeType: \"video/mp4\")\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// Access files using the `url` or `path` fields\nlet txt = Files.testTxt.url\nlet video = Files.Subdir.aVideoWithSpacesMp4.path\n\n// In addition, there are `url(locale:)` and `path(locale:)` to specify a locale\nlet localeTxt = Files.testTxt.url(locale: Locale.current)\nlet localeVideo = Files.Subdir.aVideoWithSpacesMp4.path(locale: Locale.current)\n```\n\n### Flat Structure Support\n\nSwiftGen also has a template if you're not interested in keeping the folder structure in the generated code.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the flat bundled template\u003c/summary\u003e\n\n```swift\ninternal enum Files {\n  /// test.txt\n  internal static let testTxt = File(name: \"test\", ext: \"txt\", path: \"\", mimeType: \"text/plain\")\n  /// subdir/A Video With Spaces.mp4\n  internal static let aVideoWithSpacesMp4 = File(name: \"A Video With Spaces\", ext: \"mp4\", path: \"subdir\", mimeType: \"video/mp4\")\n  }\n}\n```\n\u003c/details\u003e\n\nGiven the same file and folder structure as above the usage will now be:\n\n```swift\n// Access files using the `url` or `path` fields\nlet txt = Files.testTxt.url\nlet video = Files.aVideoWithSpacesMp4.path\n\n// In addition, there are `url(locale:)` and `path(locale:)` to specify a locale\nlet localeTxt = Files.testTxt.url(locale: Locale.current)\nlet localeVideo = Files.aVideoWithSpacesMp4.path(locale: Locale.current)\n```\n\n## Fonts\n\n```yaml\nfonts:\n  inputs: /path/to/font/dir\n  outputs:\n    templateName: swift5\n    output: Fonts.swift\n```\n\nThis 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.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal enum FontFamily {\n  internal enum SFNSDisplay: String, FontConvertible {\n    internal static let regular = FontConvertible(name: \".SFNSDisplay-Regular\", family: \".SF NS Display\", path: \"SFNSDisplay-Regular.otf\")\n  }\n  internal enum ZapfDingbats: String, FontConvertible {\n    internal static let regular = FontConvertible(name: \"ZapfDingbatsITC\", family: \"Zapf Dingbats\", path: \"ZapfDingbats.ttf\")\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// You can create fonts with the convenience constructor like this:\nlet displayRegular = UIFont(font: FontFamily.SFNSDisplay.regular, size: 20.0) // iOS\nlet dingbats = NSFont(font: FontFamily.ZapfDingbats.regular, size: 20.0)  // macOS\n\n// Or as an alternative, you can refer to enum instance and call .font on it:\nlet sameDisplayRegular = FontFamily.SFNSDisplay.regular.font(size: 20.0)\nlet sameDingbats = FontFamily.ZapfDingbats.regular.font(size: 20.0)\n```\n\n## Interface Builder\n\n```yaml\nib:\n  inputs: /dir/to/search/for/storyboards\n  outputs:\n    - templateName: scenes-swift5\n      output: Storyboard Scenes.swift\n    - templateName: segues-swift5\n      output: Storyboard Segues.swift\n```\n\nThis will generate an `enum` for each of your `NSStoryboard`/`UIStoryboard`, with respectively one `static let` per storyboard scene or segue.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\nThe generated code will look like this:\n\n```swift\n// output from the scenes template\n\ninternal enum StoryboardScene {\n  internal enum Dependency: StoryboardType {\n    internal static let storyboardName = \"Dependency\"\n\n    internal static let dependent = SceneType\u003cUIViewController\u003e(storyboard: Dependency.self, identifier: \"Dependent\")\n  }\n  internal enum Message: StoryboardType {\n    internal static let storyboardName = \"Message\"\n\n    internal static let messagesList = SceneType\u003cUITableViewController\u003e(storyboard: Message.self, identifier: \"MessagesList\")\n  }\n}\n\n// output from the segues template\n\ninternal enum StoryboardSegue {\n  internal enum Message: String, SegueType {\n    case customBack = \"CustomBack\"\n    case embed = \"Embed\"\n    case nonCustom = \"NonCustom\"\n    case showNavCtrl = \"Show-NavCtrl\"\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// You can instantiate scenes using the `instantiate` method:\nlet vc = StoryboardScene.Dependency.dependent.instantiate()\n\n// You can perform segues using:\nvc.perform(segue: StoryboardSegue.Message.embed)\n\n// or match them (in prepareForSegue):\noverride func prepare(for segue: UIStoryboardSegue, sender: Any?) {\n  switch StoryboardSegue.Message(segue) {\n  case .embed?:\n    // Prepare for your custom segue transition, passing information to the destination VC\n  case .customBack?:\n    // Prepare for your custom segue transition, passing information to the destination VC\n  default:\n    // Other segues from other scenes, not handled by this VC\n    break\n  }\n}\n```\n\n## JSON and YAML\n\n```yaml\njson:\n  inputs: /path/to/json/dir-or-file\n  outputs:\n    templateName: runtime-swift5\n    output: JSON.swift\nyaml:\n  inputs: /path/to/yaml/dir-or-file\n  outputs:\n    templateName: inline-swift5\n    output: YAML.swift\n```\n\nThis 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.\n\nUnlike other parsers, this one 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 parsers (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](Documentation/Articles/Creating-custom-templates.md).\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal enum JSONFiles {\n  internal enum Info {\n    private static let _document = JSONDocument(path: \"info.json\")\n    internal static let key1: String = _document[\"key1\"]\n    internal static let key2: String = _document[\"key2\"]\n    internal static let key3: [String: Any] = _document[\"key3\"]\n  }\n  internal enum Sequence {\n    internal static let items: [Int] = objectFromJSON(at: \"sequence.json\")\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// This will be a dictionary\nlet foo = JSONFiles.Info.key3\n\n// This will be an [Int]\nlet bar = JSONFiles.Sequence.items\n```\n\n## Plists\n\n```yaml\nplist:\n  inputs: /path/to/plist/dir-or-file\n  outputs:\n    templateName: runtime-swift5\n    output: Plist.swift\n```\n\nThis 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.\n\nUnlike other parsers, this one 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 parser (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](Documentation/Articles/Creating-custom-templates.md).\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the bundled template\u003c/summary\u003e\n\n```swift\ninternal enum PlistFiles {\n  internal enum Test {\n    internal static let items: [String] = arrayFromPlist(at: \"array.plist\")\n  }\n  internal enum Stuff {\n    private static let _document = PlistDocument(path: \"dictionary.plist\")\n    internal static let key1: Int = _document[\"key1\"]\n    internal static let key2: [String: Any] = _document[\"key2\"]\n  }\n}\n```\n\u003c/details\u003e\n\n### Usage Example\n\n```swift\n// This will be an array\nlet foo = PlistFiles.Test.items\n\n// This will be an Int\nlet bar = PlistFiles.Stuff.key1\n```\n\n## Strings\n\n```yaml\nstrings:\n  inputs: /path/to/language.lproj\n  outputs:\n    templateName: structured-swift5\n    output: Strings.swift\n```\n\nThis will generate a Swift `enum L10n` that will map all your `Localizable.strings` and `Localizable.stringsdict` (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. By default it will add comments to the generated constants and functions using the comments from the strings file if present, or the default translation of the string.\n\n\u003e Note that all dots within the key names are converted to dots in code (by using nested enums). You can provide a different separator than `.` to split key names into substructures by using a parser option – see [the parser documentation](Documentation/Parsers/strings.md).\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the structured bundled template\u003c/summary\u003e\n\nGiven the following `Localizable.strings` file:\n\n```swift\n/* Title for an alert */\n\"alert_title\" = \"Title of the alert\";\n\"alert_message\" = \"Some alert body there\";\n/* A comment with no space above it */\n\"bananas.owner\" = \"Those %d bananas belong to %@.\";\n```\n\nAnd the following `Localizable.stringsdict` file:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003cplist version=\"1.0\"\u003e\n  \u003cdict\u003e\n    \u003ckey\u003eapples.count\u003c/key\u003e\n    \u003cdict\u003e\n        \u003ckey\u003eNSStringLocalizedFormatKey\u003c/key\u003e\n        \u003cstring\u003e%#@apples@\u003c/string\u003e\n        \u003ckey\u003eapples\u003c/key\u003e\n        \u003cdict\u003e\n            \u003ckey\u003eNSStringFormatSpecTypeKey\u003c/key\u003e\n            \u003cstring\u003eNSStringPluralRuleType\u003c/string\u003e\n            \u003ckey\u003eNSStringFormatValueTypeKey\u003c/key\u003e\n            \u003cstring\u003ed\u003c/string\u003e\n            \u003ckey\u003ezero\u003c/key\u003e\n            \u003cstring\u003eYou have no apples\u003c/string\u003e\n            \u003ckey\u003eone\u003c/key\u003e\n            \u003cstring\u003eYou have one apple\u003c/string\u003e\n            \u003ckey\u003eother\u003c/key\u003e\n            \u003cstring\u003eYou have %d apples. Wow that is a lot!\u003c/string\u003e\n        \u003c/dict\u003e\n    \u003c/dict\u003e\n  \u003c/dict\u003e\n\u003c/plist\u003e\n```\n\n\u003e _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 😉_\n\nThe generated code will contain this:\n\n```swift\ninternal enum L10n {\n  /// Some alert body there\n  internal static let alertMessage = L10n.tr(\"Localizable\", \"alert__message\", fallback: #\"Some alert body there\"#)\n  /// Title for an alert\n  internal static let alertTitle = L10n.tr(\"Localizable\", \"alert__title\", fallback: #\"Title of the alert\"#)\n  internal enum Apples {\n    /// You have %d apples\n    internal static func count(_ p1: Int) -\u003e String {\n      return L10n.tr(\"Localizable\", \"apples.count\", p1, fallback: #\"You have %d apples\"#)\n    }\n  }\n  internal enum Bananas {\n    /// A comment with no space above it\n    internal static func owner(_ p1: Int, _ p2: Any) -\u003e String {\n      return L10n.tr(\"Localizable\", \"bananas.owner\", p1, String(describing: p2), fallback: #\"Those %d bananas belong to %@.\"#)\n    }\n  }\n}\n```\nNote that if the same key is present in both the `.strings` and the `.stringsdict` files, SwiftGen will only consider the one in the `.stringsdict` file, as that's also how Foundation behaves at runtime.\n\n\u003c/details\u003e\n\n### Usage Example\n\nOnce the code has been generated by the script, you can use it this way in your Swift code:\n\n```swift\n// Simple strings\nlet message = L10n.alertMessage\nlet title = L10n.alertTitle\n\n// with parameters, note that each argument needs to be of the correct type\nlet apples = L10n.Apples.count(3)\nlet bananas = L10n.Bananas.owner(5, \"Olivier\")\n```\n\n### Flat Strings Support\n\nSwiftGen also has a template to support flat strings files (i.e. without splitting the keys in substructures using \"dot syntax\"). The advantage is that your keys won't be mangled in any way; the disadvantage is that auto-completion won't be as nice.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample of code generated by the flat bundled template\u003c/summary\u003e\n\n```swift\ninternal enum L10n {\n  /// Some alert body there\n  internal static let alertMessage = L10n.tr(\"Localizable\", \"alert__message\", fallback: #\"Some alert body there\"#)\n  /// Title for an alert\n  internal static let alertTitle = L10n.tr(\"Localizable\", \"alert__title\", fallback: #\"Title of the alert\"#)\n  /// You have %d apples\n  internal static func applesCount(_ p1: Int) -\u003e String {\n    return L10n.tr(\"Localizable\", \"apples.count\", p1, fallback: #\"You have %d apples\"#)\n  }\n  /// A comment with no space above it\n  internal static func bananasOwner(_ p1: Int, _ p2: Any) -\u003e String {\n    return L10n.tr(\"Localizable\", \"bananas.owner\", p1, String(describing: p2), fallback: #\"Those %d bananas belong to %@.\"#)\n  }\n}\n```\n\u003c/details\u003e\n\nGiven the same `Localizable.strings` and `Localizable.stringsdict` as above the usage will now be:\n\n```swift\n// Simple strings\nlet message = L10n.alertMessage\nlet title = L10n.alertTitle\n\n// with parameters, note that each argument needs to be of the correct type\nlet apples = L10n.applesCount(3)\nlet bananas = L10n.bananasOwner(5, \"Olivier\")\n```\n\n---\n\n# Licence\n\nThis code and tool is under the MIT Licence. See the `LICENCE` file in this repository.\n\n## Attributions\n\nThis tool is powered by\n\n- [Stencil](https://github.com/stencilproject/Stencil) and few other libs by [Kyle Fuller](https://github.com/kylef)\n- SwiftGenKit and [StencilSwiftKit](https://github.com/SwiftGen/StencilSwiftKit), our internal frameworks at SwiftGen\n\nIt is currently mainly maintained by [@AliSoftware](https://github.com/AliSoftware) and [@djbe](https://github.com/djbe). But I couldn't thank enough all the other [contributors](https://github.com/SwiftGen/SwiftGen/graphs/contributors) to this tool along the different versions which helped make SwiftGen awesome! 🎉\n\nIf you want to contribute, don't hesitate to open a Pull Request, or even join the team!\n\n## Other Libraries / Tools\n\nIf you want to also get rid of String-based APIs not only for your resources, but also for `UITableViewCell`, `UICollectionViewCell` and XIB-based views, you should take a look at my Mixin [Reusable](https://github.com/AliSoftware/Reusable).\n\nIf 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](https://github.com/krzysztofzablocki/Sourcery).\n\n_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!_\n\nYou can also [follow me on twitter](http://twitter.com/aligatr) for news/updates about other projects I am creating, or [read my blog](https://alisoftware.github.io).\n","funding_links":[],"categories":["Swift","Libs","WebSocket"],"sub_categories":["Colors"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAliSoftware%2FSwiftGen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FAliSoftware%2FSwiftGen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FAliSoftware%2FSwiftGen/lists"}