Vincenzo Flaminio
Vincenzo Flaminio

Reputation: 21

String Catalog not working for all string

As in the title when I build the project only some of the string are in the file localizable.

I read this on the official documentation:

When enabled, literal strings in SwiftUI will be extracted during localization export. This will only extract string literals in Text() initializers, unless SWIFT_EMIT_LOC_STRINGS is also enabled.

I set the value on true but nothing changed.

For example I have a view:

   IntroView(
            title: "titleTest",
            subtitle: "subtitleTest",
            actionTitle: "ActionTest") {
                print("testAction")
            }

In the localizable I don't have these strings, but only the ones that are in a Text() initializers.

Upvotes: 1

Views: 718

Answers (1)

Sweeper
Sweeper

Reputation: 270733

Strings are only added to the string catalog only when a string literal is in a place where a localized string type (e.g. LocalizedStringKey) is expected. Text has such an initialiser, so it works for Text.

You should write your view's initialiser to take LocalizedStringKeys instead of Strings.

init(title: LocalizedStringKey, subtitle: LocalizedStringKey, actionTitle: LocalizedStringKey, action: @escaping () -> Void) {
    // assuming you are going to assign these to properties in IntroView,
    // you should change the types of those properties to LocalizedStringKey too
}

Most SwiftUI views have initialisers that take a LocalizedStringKey, so most likely this change will not affect other parts of your code. If you do have some code that needs to perform string operations on the localisation key for some reason, you can take a LocalizedStringResource instead, from which you can access its key.

Upvotes: 1

Related Questions