Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create string template in Swift?

Tags:

string

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?

like image 810
TruMan1 Avatar asked Apr 03 '15 00:04

TruMan1


2 Answers

You already have an answer, but if you want type safety and to localize your code, you can use enums like this:

enum Greeting: CustomStringConvertible {

    case SayHello(String)

    var description:String {
        switch (self) {
        case .SayHello(let name):
            return "Say hello to \(name)?"
        }
    }
}

let a = Greeting.SayHello("my little friend")

Note that doesn't preclude you from taking a hybrid approach of putting all your string templates in one location and building them in a type safe enum via the String(format:...) approach. You would just need to implement it carefully (but only once).

like image 124
Chris Conover Avatar answered Oct 28 '22 16:10

Chris Conover


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.

like image 34
kellanburket Avatar answered Oct 28 '22 18:10

kellanburket