Search code examples
swiftnslocalizedstringformatted

NSLocalizedString(key: value: comment: ) with variable is not working in swift


I need to localize a string which has some variable and the localized string must be defined with key: value: comment format. Guys I tried many ways but don't get the right way yet. See here...

let timeValue = 5
let timeString = "hours"

//Bellows are working fine
dateLabelString = String(format: "Overdue by %d %@", timeValue,timeString) //Working  //Normal flat string
dateLabelString = String(format: NSLocalizedString("Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) //Working
dateLabelString = String.localizedStringWithFormat(NSLocalizedString("Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) //Working

dateLabelString = NSString.init(format: "Overdue by %d %@", timeValue,timeString) as String //Working
dateLabelString = NSString.init(format: NSLocalizedString("Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) as String //Working


//Bellows are not working 
dateLabelString = String(format: NSLocalizedString("OVERDUE_BY", value: "Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) //Not Working
dateLabelString = String.localizedStringWithFormat(NSLocalizedString("OVERDUE_BY", value: "Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) //Not Working
dateLabelString = NSString.init(format: NSLocalizedString("OVERDUE_BY", value: "Overdue by %d %@", comment: "Overdue by 5 days/hours/minutes/seconds"), timeValue,timeString) as String //Not Working

Xcode: 8.2.1 Swift: 2.3

Notice the problem is for including the key on NSLocalizedString, otherwise its working perfectly. I need the key must.


Solution

  • For localized strings with variables this is working for me:

    String.localizedStringWithFormat(NSLocalizedString("MyCustomKey", comment: "Hello %d World"), myValue)
    

    And in the Localizable.strings this line:

    MyCustomKey = "Hello %d World";