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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Better use "Build %@, %ld" or it'll crash :)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.