2

I've got text in my app that's supposed to be localized, like

  Text(self.model.stringValue)

where .stringValue = "dist", and I've created Localized.strings and added the reference

  "dist" = "the distance";

The documentation says that Text views automatically interpret strings as localization keys and look them up for you:

 Text("pencil") // Searches the default table in the main bundle.

I've clicked "Localize" on the strings file and added languages to the project file and answers like this say it's supposed to just work: How to implement localization in Swift UI

But instead it's just displaying "dist" instead of the proper localized string. What am I doing wrong?

c roald
  • 1,984
  • 1
  • 20
  • 30

2 Answers2

3

You can make it localized inline, as

Text(LocalizedStringKey(self.model.stringValue))
Asperi
  • 228,894
  • 20
  • 464
  • 690
2

It turns out that the string in Text("pencil") is only interpreted as a localization key if you pass it as a literal. If you pass a variable of type String, this doesn't happen. The answer is instead to declare the variable of type LocalizedStringKey.

  Text("dist") //-> implicitly treats string literal as a key; looks up and displays "the distance"
  let cap1:String = "dist"
  Text(cap1)   //-> no lookup for explicit String variable; just displays "dist"
  let cap2:LocalizedStringKey = "dist"
  Text(cap2)   //-> looks up explicit LocalizedStringKey value; displays "the distance"
c roald
  • 1,984
  • 1
  • 20
  • 30