2

How can I translate a string that has a variable in it like this:

let alert = UIAlertController(title: NSLocalizedString("NEUEARTIKEL",comment:"Bitte gib einen neuen Artikel für \(titelArr[sender.tag]) an:"), message: nil, preferredStyle: .Alert)

When I just translate the String normally like this in the localizable.string:

NEUEARTIKEL="Add an item to \(titelArr[sender.tag]):";

The alert will show (titelArr[sender.tag]) instead of its value.

This is probably very simple, but I`m new to swift an wasn't able to google something helpful! ;-)

Thanks for your help //Seb

shim
  • 9,289
  • 12
  • 69
  • 108
Seb
  • 983
  • 1
  • 11
  • 26
  • Possible duplicate of [NSLocalizedString with swift variable](http://stackoverflow.com/questions/26277626/nslocalizedstring-with-swift-variable) – shim Dec 16 '16 at 20:13
  • Possible duplicate of [NSLocalizedString with variables Swift](http://stackoverflow.com/questions/26684868/nslocalizedstring-with-variables-swift) – bauerMusic May 03 '17 at 14:08

3 Answers3

6

In your localisable, you can't setup a custom text directly, you can only use text and format flags. So, in order to get your goal, you can do this:

NEUEARTIKEL="Add an item to %@:";

After that, get your title well-formatted using NSString(format: <#NSString#>, <#args: CVarArgType#>...)

let title = NSString(format: NSLocalizedString("NEUEARTIKEL", nil), titelArr[sender.tag])
let alert = UIAlertController(title: title, message: nil, preferredStyle: .Alert)

Once that done, your localizable string will be formatted as you want.

tbaranes
  • 3,560
  • 1
  • 23
  • 31
6

This is another way and how I do it.

let NEUEARTIKEL = "Add an item to %@:"
let alert = UIAlertController(title: String.localizedStringWithFormat(NSLocalizedString(NEUEARTIKEL, comment: "Bitte gib einen neuen Artikel für \(titelArr[sender.tag]) an:"), titelArr[sender.tag]), message: nil, preferredStyle: .Alert)

basically, the main idea of Localized String with format is like this:

let math = "Math"
let science = "Science"
String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science)
r_19
  • 1,858
  • 1
  • 20
  • 16
1
let myString = String(format: NSLocalizedString("account.by_user", comment: "any comment"), "Peter","Larry")

let title = String(format:
            NSLocalizedString("account.user_count", comment: ""),
                           users.count.description)

You can find gist here

ymutlu
  • 6,585
  • 4
  • 35
  • 47