这似乎是一个非常基本的问题,但我似乎无法在任何地方找到答案:-(我可以在 Objective C 中做到这一点,但我被 Swift 卡住了。
我需要做的:
- 取一个整数值
- 将其格式化为本地化字符串
- 使用
stringWithFormat
等效方法将值注入(inject)另一个字符串(因为另一个字符串也已本地化,下面的简化示例中未显示)
如何在 Objective C 中轻松完成 - 这是可行的:
// points is of type NSNumber *
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *ptsString = [formatter stringFromNumber:points];
NSString *message = [NSString stringWithFormat:@"You've earned %@ points", ptsString];
我在 Swift 中的最佳尝试——最后一行编译器错误:
// points is of type Int
let formatter = NSNumberFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let ptsString = formatter.stringFromNumber(points)!
let message = String(format: "You've earned %@ points", arguments: ptsString)
我在最后一行的 Xcode 中收到以下错误:
"Cannot convert value of type 'String' to expected argument type '[CVarArgType]'"
(在我的实际代码中,我要插入点值的消息本身也是本地化的,但我简化了这个示例,因为在这两种情况下我都得到了完全相同的错误。)
我在这里错过了什么......?
非常感谢您的帮助,
埃里克
最佳答案
您需要将参数包装在一个集合中。像这样:
let message = String(format: "You've earned %@ points", arguments: [ptsString])
你也可以使用这个方法:
let message = "You've earned \(ptsString) points"
此外,您可以创建一个扩展方法来执行此操作:
extension String {
func format(parameters: CVarArgType...) -> String {
return String(format: self, arguments: parameters)
}
}
现在你可以这样做了:
let message = "You've earned %@ points".format("test")
let message2params = "You've earned %@ points %@".format("test1", "test2")
关于ios - 在 Swift 中,如何将格式化的 Int 值插入到 String 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791566/