SwiftUI Localization Issue

569 Views Asked by At

I have a project with two targets representing two different final products. Until now the localization was shared between the two targets, but now I have just one string to be localized differently according to the active target. In order to avoid duplicating the Localizable.string file ad tweak the file target membership, I decided to create two different Localizable-Ext.string files containing just the string to be translated differently for each target.

I'm using the SwiftUI Text initializer accepting a LocalizedStringKey parameter which automatically looks up the corresponding translation inside the file. This is what has to be done in most cases. I noticed that this initializer also accepts a tableName parameter corresponding to the .string filename where the match should be taken.

What I'm trying to achieve is to have a custom Text initializer which takes the string key, looks up for it inside the default Localizable.string file and, if no match is found, falls back to the right file extension (string table) and search for it there. Apparently this is tough to achieve since I cannot manage to get the key value from the LocalizedStringKey instance.

1

There are 1 best solutions below

0
On

I think you need something like

extension Text {
    public init<S>(looking text: S) where S : StringProtocol {
        let text = String(text)
        var translated = NSLocalizedString(text, comment: "")

        // returns same if no translation, so ...
        if translated == text {
            // ... continue in other table
            translated = NSLocalizedString(text, tableName: "Localizable-Ext",
                bundle: .main, value: text, comment: "")
        }
        // already translated, so avoid search again
        self.init(verbatim: translated)
    }
}