For the reason that localised string has format specifiers, you also needs to add the format specifiers to the important thing.
// .strings:
"turn_off_feature_format %@" = "Flip off %@";
"feature_1_title" = "Characteristic 1";
"feature_2_title" = "Characteristic 2";
Because of the customized string interpolation offered by LocalizedStringKey.StringInterpolation
, this lets you immediately format the string when making a LocalizedStringKey
.
// this creates a LocalizedStringKey similar to
// the "turn_off_feature_format %@" key within the .strings file,
// with the placeholder changed with no matter "characteristic" is
let key: LocalizedStringKey = "turn_off_feature_format (characteristic)"
If characteristic
is a LocalizedStringResource
, it will get localised too.
Figuring out that, we will write one thing like this:
extension LocalizedStringKey {
static func turnOff(characteristic: LocalizedStringResource) -> LocalizedStringKey {
"turn_off_feature_format (characteristic)"
}
}
extension LocalizedStringResource {
static let feature1 = Self("feature_1_title")
static let feature2 = Self("feature_2_title")
}
(Additionally take into account making an enum to symbolize the options)
Then you’ll be able to create Textual content
s like this:
Textual content(.turnOff(characteristic: .feature1))
Textual content(.turnOff(characteristic: .feature2))
// this additionally works:
Textual content(.feature1)
If you cannot change the localisation keys, I feel you might be caught with utilizing String(format:_:)
to do the formatting. I am unsure why you might be struggling to eliminate the duplicate string literal although. It will possibly simply be extracted to a different computed property:
var format: String {
String(localized: "turn_off_feature_format")
}
extension LocalizedStringKey {
static var turnOffFeature1: Self {
LocalizedStringKey(stringLiteral: String(
format: format,
String(localized: "feature_1_title")
))
}
static var turnOffFeature2: Self {
LocalizedStringKey(stringLiteral: String(
format: format,
String(localized: "feature_2_title")
))
}
}
That mentioned, it would not make sense for these to be LocalizedStringKey
s anymore, since you do not even have a keys known as Flip off Characteristic 1
and so forth. These ought to simply be String
s. I might put them in an enum:
enum Options: String {
case feature1 = "feature_1_title"
case feature2 = "feature_2_title"
non-public static var format: String {
String(localized: "turn_off_feature_format")
}
var turnOffLocalized: String {
String(
format: Self.format,
String(localized: .init(rawValue))
)
}
// for getting solely the names of the options
var key: LocalizedStringKey {
.init(rawValue)
}
}
e.g.
Textual content(Options.feature1.key)
Textual content(Options.feature1.turnOffLocalized)