Swift 自定义字符串格式扩展始终返回 0

发布于 2025-01-14 16:10:38 字数 363 浏览 2 评论 0原文

我需要自定义字符串格式扩展,但我有一些字符串格式问题。

这是代码。

print(String(format: "%.1f", 1.12))
print(String.format("%.1f", 1.12))
extension String {
    static func format(_ format: String, _ arguments: CVarArg...) -> String {
        return String(format: format, arguments)
    }
}

输出

1.1
0.0

为什么输出不一样?谢谢!

I need my custom string format extension but I have some string format problem.

Here's code.

print(String(format: "%.1f", 1.12))
print(String.format("%.1f", 1.12))
extension String {
    static func format(_ format: String, _ arguments: CVarArg...) -> String {
        return String(format: format, arguments)
    }
}

output

1.1
0.0

Why the outputs not the same? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-01-21 16:10:38

我认为发生这种情况是因为扩展中格式函数的返回类型是 (_ format: String, _ argument: CVarArg...) 。 return 必须是 String(format: String, Arguments:[CVarArg]) 。函数中的参数 arguments[CVarArg] 的类型,并且如果您在返回字符串格式类型中使用_arguments: CVarArg...而不是[CVarArg]arguments的参数将是[[CVarArg]]。现在它实际上是二维数组。可能会因此而失败。

这也行不通

 print(String(format: "%.1f", [1.12])) // args is CVarArg...

I think it happens because return type of the format function in extension is (_ format: String, _ arguments: CVarArg...) . return must be String(format: String, arguments:[CVarArg]) .Parameter argumentsin function is type of [CVarArg] and If you use _ arguments: CVarArg... instead of [CVarArg] in return String format type , the parameter of the arguments gonna be [[CVarArg]]. It is actually 2d array right now . It may fail because of this.

Also this is not works too

 print(String(format: "%.1f", [1.12])) // args is CVarArg...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文