Search code examples
swiftswiftui

How to get string value from LocalizedStringKey?


I'm localizing my SwiftUI app with using LocalisedStringKey and the help of the following code:

Text(l10n.helloWorld)

Where l10n is:

enum l10n {
   internal static let helloWorld = LocalizedStringKey("hello.world")
}

Where "hello.world" is defined in the file Localizable.strings:

"hello.world" = "Hello world !";

While this code works in SwiftUI's View like this:

...
Text(i18n.helloWorld)
...

I can't find a way to get l10n value from LocalizedStringKey in code behind like this:

l10n.helloWorld.toString()

Solution

  • If your use case allows it, I recommend using LocalizedStringResource instead. It works with SwiftUI and provides public access to key, defaultValue, etc.

    enum l10n {
        internal static let helloWorld = LocalizedStringResource("hello.world")
    }
    
    extension LocalizedStringResource {
        func toString() -> String {
            String(localized: self)
        }
    }
    
    Text(l10n.helloWorld)
    print(l10n.helloWorld.toString())
    

    While the other solutions work, they are not ideal because accessing internal APIs could get your app rejected.