Search code examples
swiftuienumslocalization

SwiftUI Localization and Enums


There are lots of general discussions about localization but none I've found thus far have addressed my issue.

I am using a Localizable.strings file and then another swift file containing an enum called LocalizationStrings. In the enum I am using static let statements so that I can avoid typo mistakes in my various files. (There's a lot to translate with more coming each day)

All of this works well, except when you have a localized string that contains string interpolation. This scenario fails because you cannot enclose the enum in quotes or it is read back as the string entered instead of being translated to what the enum actually equates to (which is the expected behavior).

Of course, taking the enum out of the equation and using string interpolation works just fine, but I would very much like to know if there's a way to continue to use the enum values, even when string interpolation exists.

Here's some code to explain:

Localizable.strings

"MY_NAME %@" = "My name is %@";
"YOUR_NAME" = "Your name is Fred";

LocalizationString.swift

enum LocalizationString {
    static let myName: LocalizedStringKey = "MY_NAME %@"
    static let yourName: LocalizedStringKey = "YOUR_NAME"
}

ContentView

struct CA_EmailVerifyView: View {

    let name = "Tom"

    var body: some View {
        VStack {
            // This works
            Text(LocalizationString.yourName)

            // This works (not using the enum)
            Text("myName \(name)")

            // This does not work (won't compile, but this is how I would love to use it)
            Text(LocalizationString.myName \(name))

            // This does not work (output is LocalizationString.myName Tom)
            Text("LocalizationString.myName \(name)")
        }
    }
}

Solution

  • The answer is much simpler than writing extensions and doing complicated work. Instead of writing a static let, when a variable is present you write a static func. This all takes place in the LocalizationString.swift file's enum and looks like this:

    static func testText(name: String) -> LocalizedStringKey { LocalizedStringKey("TEST_TEXT \(name)") }
    

    To use this in your view:

    Text(LocalizationStrings.testTest(name: varname))
    

    If you need more variables, just add them into the function.