TruMan1 TruMan1 - 4 months ago 19
Swift Question

Create string template in Swift?

I would like to store a string as a constant in Swift so I can reuse it and inject variables into it. For example, I can do this in C#:

var template = "Your name is {0} and your age is {1}."
someLabel.text = string.Format(template, "John", 35)
some2Label.text = string.Format(template, "Jane", 33)


How can I accomplish this in Swift so I can reuse the string template?

Answer

Use swift's printf-style syntax to save the template and then use it like this:

var template = "Your name is %@ and your age is %d."
someLabel.text = String(format: template, "John", 35)
some2Label.text = String(format: template, "Jane", 33)

If you haven't used this style of syntax before here is a rough guide:

  • %@ : String (or, as nhgrif pointed out, the description / descriptionWithLocale property of an NSObject)
  • %d : Int
  • %f : Double
  • %.2f : Double with precision of 2, e.g. 2.2342 -> 2.23

Here's the documentation if you require more precision.

Comments