Skip to content

Instantly share code, notes, and snippets.

@omochi
Created April 15, 2021 10:35
Show Gist options
  • Select an option

  • Save omochi/03a1b844ea82b441f4b2537dbe5a09e3 to your computer and use it in GitHub Desktop.

Select an option

Save omochi/03a1b844ea82b441f4b2537dbe5a09e3 to your computer and use it in GitHub Desktop.
import Foundation
private class BundleToken {}
extension Bundle {
static var current: Bundle {
Bundle(for: BundleToken.self)
}
func localized(locale: Locale) -> Bundle? {
guard let dir = url(forResource: locale.identifier, withExtension: "lproj"),
let bundle = Bundle(url: dir) else { return nil }
return bundle
}
}
private let isSwiftUIPreview: Bool = {
guard let str = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"],
let value = Int(str),
value != 0 else { return false }
return true
}()
private let isInterfaceBuilder: Bool = {
#if TARGET_INTERFACE_BUILDER
return true
#else
return false
#endif
}()
struct LocalizeKey {
var value: String
init(_ value: String) {
self.value = value
}
func string(table: String?) -> String {
var bundle = Bundle.current
if isInterfaceBuilder || isSwiftUIPreview,
let jaBundle = bundle.localized(locale: .ja)
{
bundle = jaBundle
}
return string(bundle: bundle, table: table)
}
func string(bundle: Bundle, table: String?) -> String {
bundle.localizedString(forKey: value, value: nil, table: table)
}
}
extension L10n {
private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String {
let format = LocalizeKey(key).string(table: table)
return String(format: format, locale: .current, arguments: args)
}
}
@omochi

omochi commented Apr 15, 2021

Copy link
Copy Markdown
Author

swiftgenの L10n.tr をカスタムテンプレートで差し替える

@omochi

omochi commented Apr 15, 2021

Copy link
Copy Markdown
Author

なぜかLocaleを指定してもだめで、ja bundleを直指定しないといけないんだよな

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment