onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
679 stars 33 forks source link

How to force localized language with SwiftGen #945

Open onmyway133 opened 1 year ago

onmyway133 commented 1 year ago

The default SwiftGen generate generated strings L10n file like this

extension L10n {
  private static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String {
    let format = BundleToken.bundle.localizedString(forKey: key, value: value, table: table)
    return String(format: format, locale: Locale.current, arguments: args)
  }
}

// swiftlint:disable convenience_type
private final class BundleToken {
  static let bundle: Bundle = {
    #if SWIFT_PACKAGE
    return Bundle.module
    #else
    return Bundle(for: BundleToken.self)
    #endif
  }()
}

It use the system-wide settings locale. In case we want to force a specific locale, we can write a custom method that find our selected language lproj bundle

When compiled, the localizable files will be under Resources folder, for example

MyApp.app/Contents/Resources/nb.lproj
extension L10n {
    private class BundleToken {}

    private static var bundle: Bundle {
        let language = Settings.language
        switch language {
        case .system:
            return Bundle(for: BundleToken.self)

        default:
            let path = Bundle.main.path(forResource: language.rawValue, ofType: "lproj")
            return Bundle(path: path ?? "") ?? .main
        }
    }

    static func tr(_ table: String, _ key: String, _ args: CVarArg..., fallback value: String) -> String {
        let format = bundle.localizedString(forKey: key, value: value, table: table)
        return String(format: format, locale: Locale.current, arguments: args)
    }
}