6

Not sure if this is possible. But I want to do this:

let version = "2.0.1"
let year = 2017
let version = "Build \(version), \(year)"

However, I want to source the version string from a localised file. ie.

let version = "2.0.1"
let year = 2017
let versionTemplate = NSLocalizedString("version.template", comment:"")
let version = ???? // Something done with versionTemplate

I've looked at using NSExpression, but it's not obvious if it can do this or how.

Anyone does this?

Ryan Poolos
  • 18,421
  • 4
  • 65
  • 98
drekka
  • 20,957
  • 14
  • 79
  • 135
  • Related: [How to format localised strings in Swift?](http://stackoverflow.com/questions/35316655/how-to-format-localised-strings-in-swift). – Martin R Mar 23 '17 at 12:57

1 Answers1

10

Totally possible

You'll want to use a String initializer rather than literals.

 let version = "2.0.1"
 let year = 2017
 let versionTemplate = String(format: NSLocalizedString("version.template", comment: ""), arguments: [version, year])
 // output: Build 2.0.1, 2017

In your localizable.strings file you need to have your template like this:

 "version.template" = "Build %@, %ld"

You can use a variety of format specifiers here. Check the documentation for all the possibilities. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1

Ryan Poolos
  • 18,421
  • 4
  • 65
  • 98
  • 5
    Better use `"Build %@, %ld"` or it'll crash :) – Martin R Mar 23 '17 at 12:54
  • 1
    Thanks guys. That's the Objective C way. I should have said I already know how to do that. But I was hoping to find a way that was closer to the way Swift does string interpolation. From reading around, it looks like Swift uses some syntactical sugar to handle it rather than providing any sort of function. So I'll have to go with the old fashioned way :-) I also looked into `String(stringWithInterpolation:)` etc which looks to be what Swift actually does. – drekka Mar 23 '17 at 13:50