xcstrings-tool icon indicating copy to clipboard operation
xcstrings-tool copied to clipboard

Demonstrate use of language overrides in documentation

Open VadimPavlov opened this issue 10 months ago • 3 comments

I know it's not a best practice, but it's common to change language inside application on the fly. It will be nice to have ability to set Bundle.current, to override it.

VadimPavlov avatar Mar 28 '24 09:03 VadimPavlov

Could you please share how you override language today when using LocalizedStringResource? The API has improved a bit since NSLocalizedString so you shouldn't need to do any bundle overrides anymore.

For example, in SwiftUI, you can just set the locale in the environment to override:

struct MyView: View {
    var body: some View {
        VStack {
            Text(.localizable.foo)
            Text(.localizable.bar)
        }
        .environment(\.locale, Locale(identifier: "fr"))
    }
}

For Foundation/UIKit, you can do something like this:

extension String {
    init(french resource: LocalizedStringResource) {
        var resource = resource
        resource.locale = Locale(identifier: "fr")

        self.init(localized: resource)
    }
}

// String(french: .localizable.foo)

liamnichols avatar Mar 28 '24 12:03 liamnichols

Ah good point, yes, overriding environment works fine for SwiftUI view. And for everything else it's good that we have an option to set locale on resource. Probably this issue can be closed, but I would love to see this as example in README, thanks!

VadimPavlov avatar Mar 28 '24 13:03 VadimPavlov

Thanks for confirming! Great to hear that this can help 🚀 I'll keep the ticket open to track updating some docs.

liamnichols avatar Mar 28 '24 14:03 liamnichols