简体   繁体   English

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

[英]In Swift, how to insert formatted Int value into String?

This seems like a super basic question, but I just can't seem to find the answer anywhere :-( I am able to do this in Objective C, but I am getting stuck in Swift. 这似乎是一个超级基本的问题,但我似乎无法在任何地方找到答案:-(我能够在Objective C中做到这一点,但我陷入了Swift的困境。

What I need to do: 我需要做什么:

  1. Take an Integer value 取整数值
  2. Format it into a localized string 将其格式化为本地化字符串
  3. Inject the value into another string using the stringWithFormat equivalent method (since the other string is localized as well, which is not shown in simplified examples below) 使用stringWithFormat等效方法将值注入另一个字符串(因为另一个字符串也是本地化的,下面的简化示例中未显示)

How it's easily done in Objective C -- this works: 如何在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];

My best attempt at doing this in Swift -- compiler error on last line: 我最好尝试在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)

I'm getting the following error in Xcode on that last line: 我在最后一行的Xcode中遇到以下错误:

"Cannot convert value of type 'String' to expected argument type '[CVarArgType]'"

(In my actual code, the message into which I want to insert the points value is itself localized as well, but I have simplified this example, as I'm getting the exact same error in both cases.) (在我的实际代码中,我想插入点值的消息本身也是本地化的,但我已经简化了这个例子,因为我在两种情况下都得到完全相同的错误。)

What am I missing here..? 我在这里想念的是什么..?

Thanks so much for any help, 非常感谢你的帮助,

Erik 埃里克

You need to wrap the arguments in a collection. 您需要将参数包装在集合中。 Like this: 像这样:

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

You can also use this method: 您也可以使用此方法:

let message   = "You've earned \(ptsString) points"

Additionally you can create an extension method to do this: 此外,您可以创建一个扩展方法来执行此操作:

extension String {
    func format(parameters: CVarArgType...) -> String {
        return String(format: self, arguments: parameters)
    }
}

Now you can do this: 现在你可以这样做:

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

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

let ptsString = String(format: "%02d", points)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM