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?
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).
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.23Here's the documentation if you require more precision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With