Initial commit.
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import Foundation
|
||||
|
||||
/// A reusable, bundle-bound localizer that resolves String Catalog entries for an explicit locale.
|
||||
///
|
||||
/// A server has no single "current" locale, so each lookup must name the locale to use. An instance is bound to the bundle whose catalog holds the strings,
|
||||
/// then invoked like a function to resolve a key in a chosen locale.
|
||||
public struct Localize: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The backend that resolves keys against the catalog.
|
||||
private let resolver: any CatalogResolving
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The outcome of reading the bundle's String Catalog.
|
||||
///
|
||||
/// Resolution degrades to returning raw keys rather than failing, so check this once at startup and warn when it is not ``CatalogState/loaded``.
|
||||
public var catalogState: CatalogState {
|
||||
resolver.state
|
||||
}
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a localizer backed by the String Catalog in the given bundle.
|
||||
/// - Parameters:
|
||||
/// - bundle: the bundle whose String Catalog contains the keys to resolve.
|
||||
/// - table: the name of the String Catalog resource, without the `.xcstrings` extension.
|
||||
public init(
|
||||
bundle: Bundle,
|
||||
table: String = "Localizable"
|
||||
) {
|
||||
self.init(resolver: StringCatalog.cached(
|
||||
bundle: bundle,
|
||||
table: table
|
||||
))
|
||||
}
|
||||
|
||||
/// Creates a localizer backed by the given resolver.
|
||||
///
|
||||
/// The seam for tests and alternative backends; the public API resolves against a bundled catalog.
|
||||
/// - Parameter resolver: the backend that resolves keys to localized strings.
|
||||
init(
|
||||
resolver: any CatalogResolving
|
||||
) {
|
||||
self.resolver = resolver
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Resolves a catalog key in the given locale.
|
||||
///
|
||||
/// Invoked by calling the instance directly, for example `localize("index.title", locale: locale)`.
|
||||
/// - Parameters:
|
||||
/// - key: the String Catalog key to look up.
|
||||
/// - locale: the locale to resolve the key in.
|
||||
/// - Returns: the localized string for the locale, the source-language string when the locale has no entry, or the key itself when the catalog has no
|
||||
/// entry for it.
|
||||
public func callAsFunction(
|
||||
_ key: String,
|
||||
locale: Locale
|
||||
) -> String {
|
||||
resolver.string(
|
||||
for: key,
|
||||
in: locale
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user