Search code examples
swiftgen

Using SwiftGen to create a nested enum for assets


I'm setting up SwiftGen in the project and want to create a nested enum of assets like shown in the docs...

image

https://github.com/SwiftGen/SwiftGen#asset-catalog

I've tried multiple ways to set up the assets catalog and different config options in the yml but I can't get the output to look like it does in the readme with multiple namespaces...

All I get is a single flat enum with all the images in it...

public enum Asset {
  public static let arrowBack = ImageAsset(name: "arrow-back")
  public static let arrowBottomRight = ImageAsset(name: "arrow-bottom-right")
  public static let arrowClockwise = ImageAsset(name: "arrow-clockwise")
  public static let arrowDouble = ImageAsset(name: "arrow-double")
  public static let arrowDown = ImageAsset(name: "arrow-down")
  public static let arrowTopRight = ImageAsset(name: "arrow-top-right")
  etc...

How do I set up SwiftGen (or the xcassets file) to generate the nested enum as shown in the docs.

Thanks


Solution

  • There are two ways to have nested enums in your Assets.swift file (generated by SwiftGen with the swift5 template).

    • Have multiple assets catalogs.

    You can give different asset catalogs in input for the same output file name.

    xcassets:
      inputs:
        - ./Assets/Styles.xcassets
        - ./Assets/Food.xcassets
      outputs:
        templateName: swift5
        output: ./Assets.swift
        params:
            publicAccess: true
    

    Here the two catalogs are in the same folder then you can simplify :

    xcassets:
      inputs: ./Assets
      outputs:
        templateName: swift5
        output: ./Assets.swift
    

    The Assets.swift content will be :

    enum Asset {
      enum Styles {
         ...
      }
      enum Food {
         ...
      }
    }
    
    • Provide namespaces to folders in the asset catalogs.

    In addition to this, when you add a folder in your asset catalog you can check the "provides namespace" option (in Identity and type inspector - here in my Food.xcasset file).

    Provides namespace option

    After that you have to specify your asset "path" when you try to access to this asset : Color("Exotic/mango")

    But most importantly, Swiftgen will generate a sub-enum with the items contained in the folder.

    Assets.swift file