XCStrings Tool Documentation

repository·main·Indexed 18 days ago

https://github.com/liamnichols/xcstrings-tool

A Swift Package Plugin that automates the generation of type-safe Swift constants from localization files, including Strings Catalogs (.xcstrings), .strings, and .stringsdict. It integrates into Xcode projects and Swift Package targets to eliminate hardcoded strings and manual boilerplate, supporting Xcode 15 and later.

Tokens
5.3K
Snippets
14
Records
25
Agent score
63%

What's inside XCStrings Tool

  1. Overview of XCStrings Tool

    main

    XCStrings Tool is a plugin designed to help developers use Xcode 15's .xcstrings (Strings Catalog) format as the single source of truth for localized strings.

    Instead of defining localized strings directly within your Swift views (which can lead to boilerplate and messy code), you define them in a Strings Catalog. The tool then generates Swift source code that allows you to access these strings using type-safe, dot-syntax properties.

    Key benefits include:

    • Concise Views: Removes localized string definitions from UI code.
    • No Boilerplate: Eliminates the need to manually maintain string constant files.
    • Comment Reuse: Automatically turns translator comments from the catalog into inline Swift documentation.
    • Legacy Support: Can also generate Swift code for projects using legacy .strings and .stringsdict formats.
    // Before: Manual string definitions in views
    Text(
        "You've seen \(dogs.count) dogs with a combined rating of \(totalRating)/\(dogs.count * 10)",
        bundle: .module,
        comment: "Summary of sightings shown at the bottom of the list"
    )
    
    // After: Using generated type-safe code
    Text(.localizable.contentSummary(dogs.count, totalRating, dogs.count * 10))
  2. Configure Strings Catalog for Code Generation

    main

    To ensure the generated Swift code matches your expectations, configure your .xcstrings files with the following settings:

    1. Key Naming: Set each string's Key to a lowerCamelCase identifier. This ensures the generated Swift constants follow standard naming conventions.
    2. Managed Setting: Ensure the Managed setting for your strings is set to Manually. If the compiler pre-populated your catalog, you may need to manually change this value.
  3. Getting Started with XCStrings Tool

    main

    XCStrings Tool integrates as a Swift Package Plugin. Depending on your project structure, follow the specific integration guide for your target type:

    • Xcode Project Targets: Follow the guide for integrating into an Xcode project target.
    • Swift Package Targets: Follow the guide for integrating into a Swift Package target.

    Once integrated, the plugin will generate source code that you can use to reference your localized strings via type-safe constants.

  4. Locate generated Swift source code

    main

    XCStrings Tool generates Swift source files containing constants for each Strings Catalog during the build process. These files are stored in a temporary directory within your Xcode DerivedData folder and are not part of your project's file tree.

    To find the path to a generated file:

    1. Open the Report navigator in Xcode.
    2. Select your most recent build.
    3. Search the build log for a message like: Run custom shell script 'XCStringsTool: Generate Swift code for ‘[YourCatalogName].xcstrings‘'.
    4. The full file path to the generated .swift file will be printed in that log entry.
  5. Add the XCStringsToolPlugin Build Tool plugin to a target

    main

    The Build Tool plugin automates code generation. It monitors your Strings Catalogs and invokes the generator whenever they are modified, writing Swift constants to your derived sources.

    1. Navigate to your project settings in Xcode.
    2. Select your desired target.
    3. Go to the Build Phases tab.
    4. Expand the Run Build Tool Plug-ins group.
    5. Click the + button.
    6. Select XCStringsToolPlugin from the list and click Add.
  6. Requirements for XCStrings Tool

    main

    To use XCStrings Tool, ensure your environment meets the following criteria:

    • Project Type: An Xcode project or a Swift Package project.
    • Xcode Version: Xcode 15 or later.
    • Localization Formats: Support for the new Strings Catalogs (.xcstrings) or legacy .strings and .stringsdict formats.
  7. Build and Verify XCStrings Tool Output

    main
    1. Trust the Plugin: When building for the first time, Xcode will prompt you to trust the plugin. Select Trust & Enable All.
    2. Verify Build Logs: After building, open the Report navigator in Xcode, select the latest build, and look for a message like: Run custom shell script 'XCStringsTool: Generate Swift code for ‘Localizable.xcstrings‘'.
    3. Access Generated Code: The generated Swift file is compiled as part of your target. You can use the generated constants directly in your code just like any other Swift constant.
  8. Use generated keys in SwiftUI

    main

    XCStrings Tool provides convenience methods to work seamlessly with SwiftUI, ensuring compatibility across different OS versions and types. The tool generates extensions for:

    • Text.init(localizable:)
    • LocalizedStringKey.init(localizable:)
    • LocalizedStringKey.localizable(_:)
    • LocalizedStringResource.localizable(_:)

    These allow you to pass generated keys directly into SwiftUI views and modifiers.

    var body: some View {
        List {
            // Using Text.init(localizable:)
            Text(localizable: .listContent)
        }
        // Using LocalizedStringKey.localizable(_:)
        .navigationTitle(.localizable(.headingTitle))
        .environment(\.locale, Locale(identifier: "fr"))
    }
  9. Generate Swift source code from Strings Catalogs or Legacy Strings files

    main

    The generate command creates Swift source code from your localization files. You should run this command once for each Strings Table you wish to process.

    Using Strings Catalogs (.xcstrings)

    Provide the path to your .xcstrings file.

    Using Legacy Strings Files (.strings and .stringsdict)

    Provide the path to the .strings file and the .stringsdict file.

    Important Note on Legacy Files:

    • Only specify input files for the source language.
    • If you must specify files for other languages, ensure they are properly embedded within .lproj directories and use the --development-language argument to filter inputs. This is required because, unlike the Strings Catalog format, the development language is not explicitly part of the legacy input structure.

    Command Syntax

    xcstrings-tool generate <inputs> ... --output <output> [options]

    ### Strings Catalog Example
    ```bash
    $ xcstrings-tool generate \ 
      ./App/Resources/Localizable.xcstrings 
      --access-level public \
      --output ./App/Sources/Localizable.swift

    Legacy Strings Example

    $ xcstrings-tool generate \
      ./App/Resources/en.lproj/Localizable.strings \
      ./App/Resources/en.lproj/Localizable.stringsdict \
      --access-level public \
      --output ./App/Sources/Localizable.swift
  10. Integrate XCStrings Tool into a Swift Package Target

    main

    You can integrate the XCStrings Tool plugin directly into any Swift Package target that contains Strings Catalog files (.xcstrings). This provides seamless generation of Swift constants for your localized strings.

    Note: Strings Catalogs are only supported on Apple Platforms.

  11. Migrate from XCStrings Tool to manual source management

    main

    If you want to stop using the XCStrings Tool Build Tool Plugin but keep the existing constants in your code, follow these steps:

    1. Locate the code: Find the generated .swift files using the Xcode Report navigator (see Locate generated Swift source code).
    2. Copy the code: Manually copy the contents of these generated files into your project's target.
    3. Verify Resource Bundle: Ensure the target containing the copied source code also contains the resource bundle that holds the original .xcstrings Strings Catalog. The localized string lookups will fail if the resource bundle is missing from the target.
    4. Remove the Plugin:
      • For Xcode Projects: Remove the XCStrings Tool plugin from your target's Build Phases.
      • For Swift Packages: Remove the plugin definition from your Package.swift file.
    5. Clean and Rebuild: Perform a clean build ( + + K) to ensure the project no longer attempts to call the plugin and uses your manually managed files instead.
  12. Build your project and trust the plugin

    main

    When building for the first time after adding the plugin, Xcode will prompt you to trust it.

    1. When the alert appears, review the plugin details.
    2. Click Trust & Enable All.
    3. Build your project.

    You can verify the plugin ran successfully by checking the Report navigator in the Xcode left sidebar. Look for a message like: Run custom shell script 'XCStringsTool: Generate Swift code for ‘[YourCatalogName].xcstrings‘'.