lundi 20 avril 2015

Is there an equivalent to the string function String(format: ...) using Swift formatting

I'm starting to like the Swift string formatting since it uses variable names in the string rather than ambiguous formatting tags like "%@"

I want to load a large string from a file that has Swift-style formatting in it (like this)

Now is the time for all good (who) to come to babble incoherently.

Then I want to feed the contents of that String variable into a statement that lest me replace "(who)" with the contents of the constant/variable who at runtime.

The code below works with a string constant as the formatting string.

let who = "programmers"
let aString = "Now is the time for all good \(who) to come to babble incoherently."

That code does formatting of a quoted string that appears in-line in my code.

Instead I want something like the code

let formatString = "Now is the time for all good %@ to come to babble incoherently."
aString = String(format: formatString, who)

But where I can pass in a Swift-style format string in a constant/variable I read from a file.

Is that possible. I didn't have any luck searching for it since I wasn't exactly sure what search terms to use.

I can always use C-style string formatting and the String class' initWithFormat method if I have to...

Aucun commentaire:

Enregistrer un commentaire