Possible to use variables and/or parameters with NSLocalizedString?

Viewed 36961

I have tried using a variable as an input parameter to NSLocalizedString, but all I am getting back is the input parameter. What am I doing wrong? Is it possible to use a variable string value as an index for NSLocalized string?

For example, I have some strings that I want localized versions to be displayed. However, I would like to use a variable as a parameter to NSLocalizedString, instead of a constant string. Likewise, I would like to include formatting elements in the parameter for NSLocalizedString, so I would be able to retrieved a localized version of the string with the same formatting parameters. Can I do the following:

Case 1: Variable NSLocalizedstring:

NSString *varStr = @"Index1";
NSString *string1 = NSLocalizedString(varStr,@"");

Case 2: Formatted NSLocalizedString:

NSString *string1 = [NSString stringWithFormat:NSLocalizedString(@"This is an %@",@""),@"Apple"];

(Please note that the variable can contain anything, not just a fixed set of strings.)

Thanks!

8 Answers
extension String {
    public var localizedString: String {
        return NSLocalizedString(self, comment: "")
    }

    public func localizedString(with arguments: [CVarArg]) -> String {
        return String(format: localizedString, arguments: arguments)
    }
}

Localizable.string:

"Alarm:Popup:DismissOperation:DeviceMessage" = "\"%@\" will send position updates on a regular basis again.";
"Global:Text:Ok" = "OK";

Usage:

let message = "Alarm:Popup:DismissOperation:DeviceMessage".localizedString(with: [name])

and

let title = "Global:Text:Ok".localizedString

If you have more than one variable in your localized string can you use this solution:

In Localizable.strings

"winpopup" = "#name# wins a #type# and get #points# points(s)"; 

And use stringByReplacingOccurrencesOfString to insert the values

NSString *string = NSLocalizedString(@"winpopup", nil); //"#name# wins a #type# and get #points# points(s)"
NSString *foo = [string stringByReplacingOccurrencesOfString:@"#name#" withString:gameLayer.turn];
NSString *fooo = [foo stringByReplacingOccurrencesOfString:@"#type#" withString:winMode];
NSString *msg = [fooo stringByReplacingOccurrencesOfString:@"#points#" withString:[NSString stringWithFormat:@"%i", pkt]];
NSLog(@"%@", msg);

This works for me:

NSMutableString *testMessage = [NSMutableString stringWithString:NSLocalizedString(@"Some localized text", @"")];
testMessage = [NSMutableString stringWithString:[testMessage stringByAppendingString:someStringVariable]];
Related