LocalizedStringResource
A reference to a localizable string, accessible from another process.
Declaration
struct LocalizedStringResourceOverview
Use LocalizedStringResource to provide localizable strings with lookups you defer to a later time.
When you create a localized string or a localized attributed string with an initializer that takes String.LocalizationValue, those initializers lookup the localized string immediately. If you want to perform the lookup at a later time, use this LocalizedStringResource type to refer to the localizable strings. Then, when you need to perform localization, create a String or AttributedString from an initializer that takes a LocalizedStringResource parameter, such as:
This approach allows you to provide localizable strings to an entirely separate process, which may use a different locale. For example, consider an app with a data model type called UserAction that uses LocalizedStringResource rather than strings for its title and description properties.
public protocol UserAction {
static var title: LocalizedStringResource { get }
static var description: LocalizedStringResource { get }
}This app (or one of its embedded frameworks) then uses these LocalizedStringResource members to defer looking up localized strings. Typically, this happens when calling out to another process over XPC.
public func perform(action: UserAction) {
...
// Send text to another process via XPC or similar.
performActionOutOfProcess(title: action.title, description: action.description)
}Then, when the other process receives the call, it can alter the locale in the LocalizedStringResource, prior to resolving the localized strings.
func performActionOutOfProcess(title: LocalizedStringResource,
description: LocalizedStringResource) {
// Set resource locales to match the current locale
// of the separate process.
var fixedTitle = title
fixedTitle.locale = .current
var fixedDescription = description
fixedDescription.locale = .current
// Look up localized strings.
let titleString = String(localized: fixedTitle)
let descriptionString = String(localized: fixedDescription)
// Use a correctly localized title/description.
}The App Intents framework uses LocalizedStringResource to perform a late resolution of localized strings. This allows the Siri UI to potentially use different localization preferences than the app providing the intent.