swiftswiftuilocalizationlocalizable.strings

Swift Localizable.xcstrings inheritance


I have a Xcode project with multiple targets.
This targets have common translations and some specific ones.
Is there a way to handle some kind of localization inheritance so if it does find a translation in one file, it checks in another one?

The idea would be to have a common Localizable.xcstrings and one for each target. Something like LocalizableTarget1.xcstrings, LocalizableTarget2.xcstrings, etc...

When there is a translation through Text(), String(localized: 'test'), etc... it first check in the LocalizableTargetX.strings and if it doesn't find it, check in the common one Localizable.xcstrings.

I'd like to be able to do that without modifying my existing codebase and having to specify the alternate table.

Would it be possible to do that? Is it possible to override the default behavior or to specify additional strings files to look into?


Solution

  • So I ended up using a Run Script in the Build phases to do the merge at build time and it's working well. The two input files are the target specific LocalizableTarget.xcstrings and the common on LocalizableDefault.xcstrings.
    At build time, using a simple node js script, I merging the two file to output the final Localizable.xcstrings and it is happened to the build Resources.

    The node js script looks like this:

    const fs = require('fs');
    
    let data1 = JSON.parse(fs.readFileSync(process.env.SCRIPT_INPUT_FILE_0));
    let data2 = JSON.parse(fs.readFileSync(process.env.SCRIPT_INPUT_FILE_1));
    let output = {
        ...data1,
        strings: {
            ...data1.strings,
            ...data2.strings,
        },
    };
    fs.writeFileSync(process.env.SCRIPT_OUTPUT_FILE_0, JSON.stringify(output, null, 4));
    

    The two file are merged and I didn't have to change anything in the code as the result is just a normal Localizable.xcstrings file.