Search code examples
stringswiftstring-formattingnslocalizedstringlocalizable.strings

Swift Formatting Localized Strings


We are using OneSky for the translating of strings. We use positional specifiers within the string files. The problem that I'm running into is when using %s in the string.

I have a string: "dist_unit_mask" = "%1$s %2$s"; which I read from the Localization.strings file and attempt to format: String(format: NSLocalizedString(@"dist_unit_mask", comment: @"Distance and Units"), dist, unit)

This causes the application to crash, but when I change the string to "dist_unit_mask" = "%1$@ %2$@";, the app does not crash. What could be causing the app to crash when using $s instead of %@? I would like to not modify the strings files after downloaded from OneSky.


Solution

  • The %s format (with or without positional specifiers) expects a C string, i.e. a pointer to a NUL-terminated sequences of char, and not a Swift string.

    If you really have to keep the %s format then

    String(format: NSLocalizedString(...),
        (dist as NSString).cStringUsingEncoding(NSUTF8StringEncoding),
        (unit as NSString).cStringUsingEncoding(NSUTF8StringEncoding))
    

    should work.