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

Eri*_*eut 4 string stringwithformat nsnumberformatter ios swift

这似乎是一个超级基本的问题,但我似乎无法在任何地方找到答案:-(我能够在Objective C中做到这一点,但我陷入了Swift的困境.

我需要做什么:

  1. 取整数值
  2. 将其格式化为本地化字符串
  3. 使用stringWithFormat等效方法将值注入另一个字符串(因为另一个字符串也是本地化的,下面的简化示例中未显示)

如何在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];
Run Code Online (Sandbox Code Playgroud)

我最好尝试在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)
Run Code Online (Sandbox Code Playgroud)

我在最后一行的Xcode中遇到以下错误:

"Cannot convert value of type 'String' to expected argument type '[CVarArgType]'"
Run Code Online (Sandbox Code Playgroud)

(在我的实际代码中,我想插入点值的消息本身也是本地化的,但我已经简化了这个例子,因为我在两种情况下都得到完全相同的错误.)

我在这里想念的是什么..?

非常感谢你的帮助,

埃里克

tot*_*tiG 13

您需要将参数包装在集合中.像这样:

let message   = String(format: "You've earned %@ points", arguments: [ptsString])
Run Code Online (Sandbox Code Playgroud)

您也可以使用此方法:

let message   = "You've earned \(ptsString) points"
Run Code Online (Sandbox Code Playgroud)

此外,您可以创建一个扩展方法来执行此操作:

extension String {
    func format(parameters: CVarArgType...) -> String {
        return String(format: self, arguments: parameters)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

let message = "You've earned %@ points".format("test")
let message2params = "You've earned %@ points %@".format("test1", "test2")
Run Code Online (Sandbox Code Playgroud)


Rus*_*ell 6

有时,你需要更多的控制 - 所以如果你需要有前导零,你可以使用'stringWithFormat'就像在objective-C中一样

let ptsString = String(format: "%02d", points)
Run Code Online (Sandbox Code Playgroud)