Swift: dynamic strings with local variable injection
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 specify a version string from a localized file. i.e.
let version = "2.0.1"
let year = 2017
let versionTemplate = NSLocalizedString("version.template", comment:"")
let version = ???? // Something done with versionTemplate
I've considered using it NSExpression
, but it's not obvious if it can do it and how.
Does anyone do this?
+3
source to share
1 answer
Fully Possible 😃
You want to use a string initializer, not 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 file, localizable.strings
you need to create your template like this:
"version.template" = "Build %@, %ld"
You can use various format specifiers here. Check the documentation for all possibilities. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1
+4
source to share