liamnichols / xcstrings-tool

A plugin to generate Swift constants for your Strings Catalogs.
https://swiftpackageindex.com/liamnichols/xcstrings-tool/documentation/documentation
MIT License
153 stars 24 forks source link

Demonstrate use of language overrides in documentation #47

Open VadimPavlov opened 4 months ago

VadimPavlov commented 4 months ago

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.

liamnichols commented 4 months ago

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)
VadimPavlov commented 4 months ago

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!

liamnichols commented 4 months ago

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