Skip to main contentSkip to docs navigation

Chassis

iOS Applications

View on GitHub

Chassis Tokens on iOS, as Swift constants in one type per file, with colors that follow the light and dark appearance, screen sizes, typography and icons.

This page was written with AI assistance and is not yet tested in production. Code examples and setup steps may need changes for a project.

Report an error in the issue tracker, and check the documentation of the platform when in doubt.

Introduction

The iOS output of Chassis Tokens is Swift. Every file declares one type, a caseless enum, with one static constant per token. Names are in PascalCase without a prefix.

The examples of this page use a repository of tokens named acme-tokens, on GitHub as acme/acme-tokens, and its app mobile and brand acme. Their values are those of the token sets that chassis-tokens init writes, which a repository changes. The build writes lines such as these of ChassisTokens.swift:

SWIFT
import UIKit

public enum ChassisTokens {
    public static let SpaceContextMedium = CGFloat(16)
    public static let ColorAccordionItemFgColor = UIColor(red: 0.090, green: 0.090, blue: 0.090, alpha: 1)
}

Colors are UIColor, sizes and numbers are CGFloat, font weights are UIFont.Weight, and everything else is a String. Sizes are in points, one point for one design pixel, and opacities are numbers from 0 to 1.

The values are UIKit values, which SwiftUI views can use too. The ios-swiftui preset writes SwiftUI values; a repository selects it for an app, as SwiftUI values describes.

Generated files

The build writes one folder for each brand and app, dist/ios/<app>/<brand>/, with one color file per theme and one number file, or one per screen when the repository has a screen group. The configuration that init writes has the themes light and dark and no screens.

FileTypeContents
ChassisTokens.swiftChassisTokensEvery token except the theme colors: base and component colors, sizes, spacing, border radii and widths, opacities, typography, shadows, strings and icons. Component colors are those of the first theme, and sizes those of the first screen when there are screens
String.swiftChassisTokensStringFont families, font weights and styles, text cases and decorations, and the SVG text of the icons
Color.swiftChassisTokensColorThe theme colors, each with the colors of the light and the dark theme
Color<Theme>.swiftChassisTokensColor<Theme>The theme colors of one theme: context, primitive and component colors, gradients and shadow colors: ColorLight.swift and ColorDark.swift
Number.swiftChassisTokensNumberSizes, spacing, border radii and widths, font sizes, line heights and opacities. With a screen group, one file and type per screen, such as NumberLarge.swift and ChassisTokensNumberLarge
Icons.xcassetsOne image set per icon

Every file declares another type, so all of them can be in one target. The string, color and number types share no names with each other. ChassisTokens repeats the constants of ChassisTokensString and of the number type, the first screen's when there are screens, and the component colors of the color type of the first theme, and adds the base colors (ColorBase…). The theme colors are in the color types by design: read ColorContext… constants from there.

Installation

An app takes the iOS files of a repository of tokens as a Swift package, from the archive of a release, or from its npm package.

Repository of tokens

A repository of tokens holds the token sets, the build configuration and the output. chassis-tokens init writes one, with the Chassis token system and the builder @chassis-ui/tokens as a development dependency. It needs Node.js 22.12 or later:

Shell
npx @chassis-ui/tokens init acme-tokens --brand acme --app mobile:ios
cd acme-tokens
git init
npm install
npm run build

The build writes the files to dist/ios/mobile/acme/. The repository commits dist/ and Package.swift, so a project that adds it, for example as a Git submodule, has the files without a build. After a change to the apps or brands of chassis.build, write Package.swift again:

Shell
npx chassis-tokens build
npx chassis-tokens swift-package

Then commit the files with a new version in package.json. The release workflow creates the tag of that version when you push to main. The quick start covers the setup and the release.

Swift package

The repository is a Swift package with one library for each app and brand, named ChassisTokens<App><Brand>, such as ChassisTokensMobileAcme. A library holds the Swift files of its folder in dist/ios/, with the icon catalog as a resource, and needs iOS 13 or later.

In Xcode, choose File → Add Package Dependencies…, enter the URL of the repository, such as https://github.com/acme/acme-tokens.git, choose a version and add the library of your brand to the app target. In a package, add the dependency to Package.swift:

SWIFT
// swift-tools-version:5.9

import PackageDescription

let package = Package(
    name: "YourApp",
    platforms: [.iOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/acme/acme-tokens.git", from: "<version>")
    ],
    targets: [
        .target(
            name: "YourApp",
            dependencies: [.product(name: "ChassisTokensMobileAcme", package: "acme-tokens")]
        )
    ]
)

Swift Package Manager resolves the tag of a release, and the package holds the files that the repository commits in dist/ios/ at that tag.

Release archive

Every release of the repository has one archive per platform, app and brand attached, such as acme-tokens-ios-mobile-acme-<version>.zip, for a project that takes the files of one brand and installs no package. It unpacks to the Swift files and Icons.xcassets. Add them to the app target, and no import is needed for the types. GitHub records the SHA-256 digest of each archive on the release, so a build script can check what it downloads.

A repository of tokens writes its own with npx chassis-tokens archive, and the release workflow that init writes attaches them.

Files from npm

The npm package of the repository holds the same files, for a project that installs its dependencies with npm:

Shell
npm install acme-tokens

Add the Swift files of node_modules/acme-tokens/dist/ios/mobile/<brand>/ and Icons.xcassets to the app target. The types are then part of the app module, and no import is needed for them. An app with one theme needs ChassisTokens.swift and one color file only.

Basic usage

Import the library and write the type before the constant. With the files in the app target, leave out the import of the library:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func makeLabel() -> UILabel {
    let label = UILabel()
    label.textColor = ChassisTokensColor.ColorContextDefaultFgMain
    label.backgroundColor = ChassisTokensColor.ColorContextDefaultBgMain
    label.layer.cornerRadius = ChassisTokens.BorderRadiusContextMedium
    return label
}

Every library declares the same types. A file that imports two libraries names the library before the type, such as ChassisTokensMobileGlobex.ChassisTokensColor.ColorContextDefaultBgMain.

SwiftUI

SwiftUI takes the CGFloat constants as they are and the colors through Color(_:), or Color(uiColor:) from iOS 15. The SwiftUI color follows the appearance as the UIColor does:

SWIFT
import ChassisTokensMobileAcme
import SwiftUI

struct Card: View {
    var body: some View {
        Text("Card")
            .foregroundColor(Color(ChassisTokensColor.ColorContextDefaultFgMain))
            .padding(ChassisTokens.SpaceContextMedium)
            .background(Color(ChassisTokensColor.ColorContextDefaultBgMain))
            .cornerRadius(ChassisTokens.BorderRadiusContextMedium)
    }
}

Themes

The color types of the themes declare the same constants, each with the colors of its theme. The configuration that init writes has the themes light and dark. When the configured themes include these two, the build also writes Color.swift, whose type ChassisTokensColor holds every theme color once. A color that differs between the two themes follows the interface style of the view that uses it. The build writes to Color.swift:

SWIFT
    public static let ColorContextDefaultBgMain = UIColor { $0.userInterfaceStyle == .dark ? UIColor(red: 0.071, green: 0.071, blue: 0.071, alpha: 1) : UIColor(red: 1.000, green: 1.000, blue: 1.000, alpha: 1) }

Use these colors in views, and the appearance of each view picks the color:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func applyTheme(to view: UIView, label: UILabel) {
    view.backgroundColor = ChassisTokensColor.ColorContextDefaultBgMain
    label.textColor = ChassisTokensColor.ColorContextDefaultFgMain
}

ChassisTokensColorLight and ChassisTokensColorDark hold the colors of one theme each, for code that needs a fixed theme. A theme with another name has its own file and type, Color<Theme>.swift and ChassisTokensColor<Theme>, and the app chooses between the types.

Screen sizes

The screen group is optional, and init writes none. A configuration without screens, with screens empty or left out of chassis.build, writes one number file without a screen suffix, Number.swift, with the type ChassisTokensNumber.

A repository that adds a screen group, with the screens large, medium and small for example, gets one number file and type per screen, such as ChassisTokensNumberLarge. Each declares the same constants with the values of one screen, and ChassisTokens has the values of the first screen. The constants that differ between screens are those that the token sets of the screens declare; this example takes a repository whose screen sets give space.context.large a value per screen.

Choose the number type for the current layout. The tokens do not tie a screen to a device or a size class, so the size class of this example is a choice of the app:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func sectionPadding(for traits: UITraitCollection) -> CGFloat {
    traits.horizontalSizeClass == .compact
        ? ChassisTokensNumberSmall.SpaceContextLarge
        : ChassisTokensNumberLarge.SpaceContextLarge
}

Typography

A typography token is split into one constant per property. The numbers are in the number types, and the build writes them to the number file, here Number.swift:

SWIFT
    public static let FontContextLeadLineHeight = CGFloat(32)
    public static let FontContextLeadFontSize = CGFloat(22)
    public static let FontContextLeadLetterSpacing = CGFloat(0)

The other properties are in ChassisTokensString: the font family, the text case, the text decoration and the font style as a String, such as FontContextLeadFontFamily, and the font weight as a UIFont.Weight, FontContextLeadFontWeight. Use the size and the weight for a system font:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func leadFont() -> UIFont {
    UIFont.systemFont(
        ofSize: ChassisTokensNumber.FontContextLeadFontSize,
        weight: ChassisTokensString.FontContextLeadFontWeight
    )
}

The constants follow these rules:

  • The font family is the first family of the list that the token holds. UIFont(name:size:) returns nil unless the app bundles and registers that font.
  • The font weight is the UIFont.Weight of the weight that the token names.
  • The line height is in points. A line height in percent is converted with the font size of the same typography token.
  • The letter spacing is in points.

Shadows

A shadow token is split into its layers and their parts. The name of a part holds the number of its layer, from 1, as in ShadowContextSmall1Blur. The build writes the numbers of a layer to the number files, with the CSS meaning of each part and with …Radius, half the blur, for the shadowRadius of Core Animation:

SWIFT
    public static let ShadowContextSmall1Blur = CGFloat(8)
    public static let ShadowContextSmall1Radius = CGFloat(4)
    public static let ShadowContextSmall1Spread = CGFloat(-2)
    public static let ShadowContextSmall1OffsetX = CGFloat(0)
    public static let ShadowContextSmall1OffsetY = CGFloat(2)

It writes the color of a layer, ShadowContextSmall1Color, to the color files as a UIColor. The color carries the opacity of the shadow in its alpha. Core Animation multiplies it by shadowOpacity, so set that to 1. A layer of Core Animation has one shadow and no spread; this function applies the first layer of the token:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func applySmallShadow(to layer: CALayer) {
    layer.shadowColor = ChassisTokensColor.ShadowContextSmall1Color.cgColor
    layer.shadowOpacity = 1
    layer.shadowOffset = CGSize(
        width: ChassisTokensNumber.ShadowContextSmall1OffsetX,
        height: ChassisTokensNumber.ShadowContextSmall1OffsetY
    )
    layer.shadowRadius = ChassisTokensNumber.ShadowContextSmall1Radius
}

cgColor takes the color of the current appearance, and the shadow colors differ between the themes. Apply the shadow again when the trait collection changes.

Gradients

A gradient token is split into its parts: the angle, and the color and the position of each stop, numbered from 1. The build writes them to the color files:

SWIFT
    public static let GradientPrimitiveBlackL000Angle = CGFloat(0)
    public static let GradientPrimitiveBlackL000Stop1Color = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 0)
    public static let GradientPrimitiveBlackL000Stop1Position = CGFloat(0)

The angle is the CSS angle in degrees: 0 points up and angles turn clockwise, so 90 runs from left to right. Positions go from 0 to 1. Turn the parts into a CAGradientLayer:

SWIFT
import ChassisTokensMobileAcme
import UIKit

typealias Tokens = ChassisTokensColor

func applyGradient(to layer: CAGradientLayer, angle: CGFloat, stops: [(UIColor, CGFloat)]) {
    let radians = angle * .pi / 180
    let dx = sin(radians) / 2
    let dy = -cos(radians) / 2
    layer.startPoint = CGPoint(x: 0.5 - dx, y: 0.5 - dy)
    layer.endPoint = CGPoint(x: 0.5 + dx, y: 0.5 + dy)
    layer.colors = stops.map { $0.0.cgColor }
    layer.locations = stops.map { NSNumber(value: Double($0.1)) }
}

func makeFade() -> CAGradientLayer {
    let fade = CAGradientLayer()
    applyGradient(to: fade, angle: Tokens.GradientPrimitiveBlackL000Angle, stops: [
        (Tokens.GradientPrimitiveBlackL000Stop1Color, Tokens.GradientPrimitiveBlackL000Stop1Position),
        (Tokens.GradientPrimitiveBlackL000Stop2Color, Tokens.GradientPrimitiveBlackL000Stop2Position)
    ])
    return fade
}

The start and end points follow the angle exactly in a square layer. In other shapes, CSS lengthens the gradient line so that the corners get the first and the last color, which these points do not.

Icons

Icons.xcassets holds one image set per icon token, named like its constant, such as IconChipRemove. An image set keeps the SVG as a vector and renders it as a template, so the icon takes the tint color. The SVG text of each icon is also a constant of ChassisTokensString.

With the Swift package, the catalog is in the resource bundle of the library, which is named after the package and the library:

SWIFT
import ChassisTokensMobileAcme
import UIKit

func removeIcon() -> UIImage? {
    let bundle = Bundle.main
        .url(forResource: "ChassisTokens_ChassisTokensMobileAcme", withExtension: "bundle")
        .flatMap(Bundle.init(url:))
    return UIImage(named: "IconChipRemove", in: bundle, compatibleWith: nil)
}

func makeRemoveButton() -> UIButton {
    let button = UIButton(type: .system)
    button.setImage(removeIcon(), for: .normal)
    button.tintColor = ChassisTokensColor.ColorContextDefaultFgMain
    return button
}

In SwiftUI, Image("IconChipRemove", bundle: bundle) takes the foreground color.

With the files in the app target, add the catalog to the target too. The icons are then in the bundle of the app: UIImage(named: "IconChipRemove") and Image("IconChipRemove").

Build options

Build options change what the generated files hold, in the repository of tokens. Set them in chassis.build of package.json.

SwiftUI values

The ios-swiftui preset writes the same types with SwiftUI values, Color and Font.Weight, to dist/ios-swiftui/<app>/<brand>/. In chassis.build of package.json:

JSON
"apps": {
  "mobile": ["ios", "ios-swiftui"]
}

The build then writes SwiftUI values, here to ChassisTokens.swift:

SWIFT
    public static let ColorAccordionItemFgColor = Color(red: 0.090, green: 0.090, blue: 0.090, opacity: 1)
    public static let TypographyFontWeightUiStrongWeight = Font.Weight.semibold

The preset writes no Color.swift and no icon catalog, and its colors have one theme each. Package.swift names the libraries of the preset ChassisTokens<App><Brand>SwiftUI. For colors that follow the appearance, use ChassisTokensColor of the ios platform, as in SwiftUI. The Style Dictionary guide describes the preset.

outputReferences

With outputReferences, a constant holds the constant of the token it references. In chassis.build of package.json:

JSON
"options": {
  "ios": { "outputReferences": true }
}

The build then writes references, here to ChassisTokens.swift:

SWIFT
    public static let SizeUnit4 = DimensionBase4
    public static let BorderRadiusAccordionMain = BorderRadiusContextMedium

The value of every constant is the same with and without the option. A constant names another only when both are in the same file and have the same type and value. Base colors, sizes computed with math and colors such as rgba({color}, {opacity}) keep their values.

Continuous integration

With the Swift package, Xcode resolves the tokens, and a workflow needs no step for them. With a repository of tokens as a submodule, check out the submodules; dist/ is committed, so the files are there. To build the tokens in the workflow, set up Node.js 22.12 or later, and build before the app:

YAML
name: Build

on: [push]

jobs:
  build:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v5
        with:
          submodules: recursive

      - uses: actions/setup-node@v5
        with:
          node-version: 22

      - name: Build tokens
        working-directory: vendor/acme-tokens
        run: |
          npm ci
          npx chassis-tokens build --platform ios

      - name: Build app
        run: xcodebuild -project YourApp.xcodeproj -scheme YourApp build

Best practices

✅ Use ChassisTokensColor in views: Its constants, such as ColorContextDefaultBgMain, follow the light and dark appearance. ChassisTokensColorLight and ChassisTokensColorDark never change.

✅ Take screen values from the number types: With a screen group, ChassisTokens has the first screen only. Read the values of a screen from its number type.

✅ Change tokens at the source: A build overwrites the files of dist/. Change the token sets in source/ and build again.

❌ Don't lower shadowOpacity: ShadowContextSmall1Color carries the opacity of the shadow in its alpha. A shadowOpacity below 1 makes the shadow lighter than the token.

❌ Don't read theme colors from ChassisTokens: The theme colors are in the color types. Read ColorContextDefaultFgMain from ChassisTokensColor, ChassisTokensColorLight or ChassisTokensColorDark.

Troubleshooting

Invalid redeclaration

The compiler stops with invalid redeclaration of 'ChassisTokens'. One file is in the target twice, or the files come from an older version, in which every file declared ChassisTokens. Add each file once, and replace files of an older version with the current ones.

Type not in scope

The compiler stops with cannot find '<type>' in scope, such as cannot find 'ChassisTokensColorLight' in scope. The file that declares the type is not in the target, or the library of the package is not imported. Add the file of the type to the target, here ColorLight.swift, or add import ChassisTokensMobileAcme to the file.

Ambiguous type

The compiler stops with ambiguous use of '<type>', such as ambiguous use of 'ChassisTokensColor'. The file imports two libraries of the package, which declare the same types. Name the library before the type, such as ChassisTokensMobileAcme.ChassisTokensColor, or import one library per file.

Missing constant

The compiler stops with type 'ChassisTokens' has no member '<constant>'. The type does not declare the constant. The theme colors are in the color types, so read ColorContext… constants from ChassisTokensColor. For another constant, check its name in the generated file: names are in PascalCase without a prefix, such as SpaceContextMedium.

Icon is nil

UIImage(named: "IconChipRemove") returns nil, without a message. With the Swift package, the catalog is in the resource bundle of the library and not in the bundle of the app. Pass that bundle, as in Icons.

Next steps