Files
ccn/Packages/Localization/Sources/Methods/Localize.swift
T

46 lines
1.4 KiB
Swift
Raw Normal View History

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 bundle whose compiled String Catalog the keys are resolved against.
private let bundle: Bundle
// MARK: Initializers
/// Creates a localizer backed by the given bundle.
/// - Parameter bundle: the bundle whose String Catalog contains the keys to resolve.
public init(
bundle: Bundle
) {
self.bundle = bundle
}
// 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, or the key itself when the bundle's catalog has no entry for it.
public func callAsFunction(
_ key: String.LocalizationValue,
locale: Locale
) -> String {
.init(localized: .init(
key,
locale: locale,
bundle: .atURL(bundle.bundleURL)
))
}
}