ios - 在 Swift 中,如何将格式化的 Int 值插入到 String 中?

标签 ios string swift nsnumberformatter stringwithformat

这似乎是一个非常基本的问题,但我似乎无法在任何地方找到答案:-(我可以在 Objective C 中做到这一点,但我被 Swift 卡住了。

我需要做的:

  1. 取一个整数值
  2. 将其格式化为本地化字符串
  3. 使用 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/

相关文章:

ios - Xcode 7 上的 IOHIDLib 和更多奇怪的错误

ios - 如何在 Swift 中切换 UITextField 安全文本输入(隐藏密码)?

java - 给出所需输出的消息格式

ios - UIScrollView 中同一个 UIView 的多个实例

ios - 这种 autoRelease 的用法有什么潜在的问题吗?

ios - 两个部分与一个 uiswitch? - swift

python - 如何在 Python 中拆分字符串,直到从右到左出现特定字符之一?

C:传递指针:不兼容的指针类型警告

swift - 匹配 "com.project.name"但不包含其他内容

swift - 迄今为止的数字 - Swift