Why is the custom localized string macro name only allowed for Objective C and C code? I have a wrapper class for localization which is a Swift function. I'm unable to get the strings i pass to it localized. Is there any way to get it working other than writing an objective C class and adding it to the bridging header?
Hello!
This does work for Swift, but the rule is that it must match the signature of one of the NSLocalizedString
overrides. NSLocalizedString
has the following signature:
func NSLocalizedString(
_ key: String,
tableName: String? = nil,
bundle: Bundle = Bundle.main,
value: String = "",
comment: String
) -> String
So as long as your custom function matches that signature (optionally excluding optional parameters), it should be extracted.
For example:
func MyLocalizedString(
_ key: String,
comment: String
) -> String
Then you can add MyLocalizedString to LOCALIZED_STRING_MACRO_NAMES.
Note that this type of extraction does not support Swift string interpolation.
Alternatively, you can rely on the Swift compiler to extract strings (SWIFT_EMIT_LOC_STRINGS), in which case you can use the LocalizedStringResource
type to carry localized strings.
func myFunctionPresentingUI(
_ title: LocalizedStringResource,
extraParam: Double
) -> String
Then at the call site:
myFunctionPresentingUI("My string", extraParam: …)
OR
myFunctionPresentingUI(LocalizedStringResource("My string", table: "CustomTable"), extraParam: …)
Using this alternative approach, you would not add myFunctionPresentingUI to LOCALIZED_STRING_MACRO_NAMES.