Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: dynamic strings with local variable injections

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?

like image 208
drekka Avatar asked Mar 23 '17 12:03

drekka


1 Answers

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

like image 120
Ryan Poolos Avatar answered Oct 05 '22 23:10

Ryan Poolos