4

I'm literally pulling my hair out trying to translate my SwiftUI app for iOS and I'm facing a wall when I need to translate a interpolated String displaying the score of the user.

I already tried some String extensions but it seems not to work correctly. For example, I have :

String Extension

extension String {

    func localized(withComment comment: String? = nil) -> String {
        return NSLocalizedString(self, comment: comment ?? "")
    }

}

Localized String in Localizable.strings

"Score" = "Perf";

The score View in ContentView.swift

ScoreCard("\("Score".localized()): \(quizManager.score)/\(quizManager.numberOfQuestions)")

which gets me to this:

enter image description here

I searched on the web and found nothing working about string interpolation for localizable strings.

Does anyone has a solution for this please?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Quentin C
  • 307
  • 3
  • 13
  • I figured out a temporary solution that is creating another **Text()** View before it and grouping both Text views in a **HStack()** like this : `HStack { Text("Score:"); Text(text) } ` – Quentin C May 21 '20 at 15:49
  • 1
    What is inside `ScoreCard`? Because if I replace it with `Text` then all works fine with your extension. Tested with Xcode 11.4 / iOS 13.4. – Asperi May 21 '20 at 17:06
  • Your extension is working perfectly. Should be considered as solution – davidev Sep 01 '20 at 07:40
  • 1
    If you're using Xcode 13 now, you could change the type of the string on the ScoreCard to be a LocalizedStringKey. Then in your Text view that uses it, just pass the variable straight in without any calls to custom "localized()" methods. SwiftUI supports looking up LocalizedStringKeys when you pass them into provided things like the Text view – FateNuller Apr 02 '22 at 17:11
  • Thank you @FateNuller I'll check that when I have some time – Quentin C Apr 05 '22 at 09:27

1 Answers1

-1

Use LocalizedStringKey in your content View

LocalizedStringKey("Score \(quizManager.score)/\(quizManager.numberOfQuestions)")
ytp92
  • 992
  • 1
  • 9
  • 8
  • 1
    Already tried it but I get the following error : _Cannot convert value of type 'LocalizedStringKey' to expected argument type 'String'_ – Quentin C May 21 '20 at 15:27
  • How did you fix this @QuentinC? – anoop4real Dec 24 '21 at 16:03
  • Nope @anoop4real I switched to another project but I'm still looking for a way to achieve it. I just don't have enough time at the moment for this problem – Quentin C Jan 13 '22 at 09:34