我想在Swift中存储一个字符串作为常量,所以我可以重用它并将变量注入其中.例如,我可以在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)
Run Code Online (Sandbox Code Playgroud)
我如何在Swift中实现这一点,以便我可以重用字符串模板?
kel*_*ket 29
使用swift的printf样式语法来保存模板,然后像这样使用它:
var template = "Your name is %@ and your age is %d."
someLabel.text = String(format: template, "John", 35)
some2Label.text = String(format: template, "Jane", 33)
Run Code Online (Sandbox Code Playgroud)
如果您之前没有使用过这种语法,那么这是一个粗略的指南:
%@:String(或者,正如nhgrif指出的那样,是description/的descriptionWithLocale属性NSObject)%d :国际 %f :双倍%.2f :精度为2的双精度,例如2.2342 - > 2.23您已经有了答案,但如果您想要类型安全并本地化您的代码,您可以使用这样的枚举:
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")
Run Code Online (Sandbox Code Playgroud)
请注意,这并不妨碍您采用混合方法将所有字符串模板放在一个位置,并通过该String(format:...)方法在类型安全枚举中构建它们.你只需要仔细地实现它(但只需要一次).
| 归档时间: |
|
| 查看次数: |
6650 次 |
| 最近记录: |