SwiftUI Text and LocalizedStringKey with parameter

3.5k Views Asked by At

I am trying to add a SwiftUI localized Text with parameter. However in the whole app we use a wrapper around localization keys so we have something like this:

static let helloWorldText = NSLocalizedString("helloWorldText", comment: "")

with usage

label.text = LocalizationWrapper.helloWorldText

or

Text(LocalizationWrapper.helloWorldText)

and it works fine.

Then when it comes to adding a localized text with parameter it doesn't seems to work.

So I have a key "helloWorld %@"

and I have a static let helloWorldWithParameter = NSLocalizedString("helloWorld %@", comment: "")

now i tried to do this:

Text("\(LocalizationWrapper.helloWorldWithParameter) \(name)")
Text(LocalizedStringKey(LocalizationWrapper.helloWorldWithParameter + " " + name))
Text(LocalizationWrapper.helloWorldWithParameter + " " + name)

none of them works, however Text("helloWorld \(name)") works just fine.

Then i tried to remove NSLocalizedString leaving only LocalizationWrapper.helloWorldWithParameter as a clean string but it allso didn't do a thing

How can I make this work? I seen THIS but it is kind of dirty.

1

There are 1 best solutions below

1
Raja Kishan On BEST ANSWER

Use this extension

extension String {
    public func localized(with arguments: [CVarArg]) -> String {
        return String(format: NSLocalizedString(self, comment: ""), locale: nil, arguments: arguments)
    }
}

Usage :

Text(LocalizationWrapper.helloWorldWithParameter.localized(with: [name]))

Also, This approach is correct

static func helloWithParameter(parameter: String) -> LocalizedStringKey {
    return "helloWorld \(parameter)"
}