3

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.

Maciej Zajda
  • 165
  • 9

1 Answers1

4

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)"
}
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52
  • 2
    This way you loose the `.enviroment` abilities that SwiftUI provides. But you can overcome that issue too https://nonameplum.github.io/posts/SwiftUI%20custom%20localization%20strings%20handling/ – sliwinski.lukas Apr 12 '22 at 13:54