2026-06-29 23:08:36 +00:00
import Foundation
/// A reusable, bundle-bound localizer that resolves String Catalog entries for an explicit locale.
///
2026-07-30 06:33:57 +00:00
/// 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.
2026-06-29 23:08:36 +00:00
public struct Localize : Sendable {
// MARK: Properties
2026-07-09 23:00:55 +00:00
/// The backend that resolves keys against the catalog.
private let resolver : any CatalogResolving
2026-06-29 23:08:36 +00:00
2026-07-28 23:37:33 +00:00
// MARK: Computed
/// The outcome of reading the bundle's String Catalog.
///
2026-07-30 06:33:57 +00:00
/// Resolution degrades to returning raw keys rather than failing, so check this once at startup and warn when it is not ``CatalogState/loaded``.
2026-07-28 23:37:33 +00:00
public var catalogState : CatalogState {
resolver . state
}
2026-06-29 23:08:36 +00:00
// MARK: Initializers
2026-07-09 23:00:55 +00:00
/// 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.
2026-06-29 23:08:36 +00:00
public init (
2026-07-09 23:00:55 +00:00
bundle : Bundle ,
table : String = "Localizable"
2026-06-29 23:08:36 +00:00
) {
2026-07-28 23:37:33 +00:00
self . init ( resolver : StringCatalog . cached (
2026-07-09 23:00:55 +00:00
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
2026-06-29 23:08:36 +00:00
}
// 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.
2026-07-30 06:33:57 +00:00
/// - 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.
2026-06-29 23:08:36 +00:00
public func callAsFunction (
2026-07-09 23:00:55 +00:00
_ key : String ,
2026-06-29 23:08:36 +00:00
locale : Locale
) -> String {
2026-07-09 23:00:55 +00:00
resolver . string (
for : key ,
in : locale
)
2026-06-29 23:08:36 +00:00
}
}